得到两张飞镖盘图像可能非正面一张为空飞镖盘一张为盘上插有飞镖现在已知飞镖落点在图上的像素坐标飞镖盘被分为20个扇形得分区且两张图像的拍摄角度相同但飞镖盘在图中不一定是正圆。如何计算这枚飞镖的得分给出python代码
要计算飞镖的得分,首先需要进行以下几个步骤:
- 载入两张飞镖盘的图像,并将它们转换为灰度图像。
import cv2
# 载入图像
empty_img = cv2.imread("empty_dartboard.jpg", 0)
dart_img = cv2.imread("dartboard_with_dart.jpg", 0)
- 对两张图像进行图像处理,提取飞镖盘的轮廓。
# 图像处理,提取轮廓
_, empty_thresh = cv2.threshold(empty_img, 127, 255, cv2.THRESH_BINARY)
_, dart_thresh = cv2.threshold(dart_img, 127, 255, cv2.THRESH_BINARY)
contours_empty, _ = cv2.findContours(empty_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours_dart, _ = cv2.findContours(dart_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
- 根据飞镖的像素坐标,计算飞镖的落点在图像中的位置。
# 飞镖落点的像素坐标
dart_x = 100
dart_y = 200
# 计算飞镖落点在图像中的位置
dart_point = (dart_x, dart_y)
- 判断飞镖的落点是否在每个得分区域内,并计算得分。
# 飞镖盘的得分区域
score_regions = 20
# 计算得分
score = -1 # 初始化得分为-1,表示未能判断得分
for i in range(score_regions):
# 获取得分区域的轮廓
empty_contour = contours_empty[i]
dart_contour = contours_dart[i]
# 判断飞镖落点是否在轮廓内
empty_point_inside = cv2.pointPolygonTest(empty_contour, dart_point, False)
dart_point_inside = cv2.pointPolygonTest(dart_contour, dart_point, False)
# 如果飞镖落点在轮廓内,则判定为相应得分
if empty_point_inside >= 0 and dart_point_inside >= 0:
score = i + 1 # 得分从1开始计算
break
完整的代码如下所示:
import cv2
# 载入图像
empty_img = cv2.imread("empty_dartboard.jpg", 0)
dart_img = cv2.imread("dartboard_with_dart.jpg", 0)
# 图像处理,提取轮廓
_, empty_thresh = cv2.threshold(empty_img, 127, 255, cv2.THRESH_BINARY)
_, dart_thresh = cv2.threshold(dart_img, 127, 255, cv2.THRESH_BINARY)
contours_empty, _ = cv2.findContours(empty_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours_dart, _ = cv2.findContours(dart_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 飞镖落点的像素坐标
dart_x = 100
dart_y = 200
# 计算飞镖落点在图像中的位置
dart_point = (dart_x, dart_y)
# 飞镖盘的得分区域
score_regions = 20
# 计算得分
score = -1 # 初始化得分为-1,表示未能判断得分
for i in range(score_regions):
# 获取得分区域的轮廓
empty_contour = contours_empty[i]
dart_contour = contours_dart[i]
# 判断飞镖落点是否在轮廓内
empty_point_inside = cv2.pointPolygonTest(empty_contour, dart_point, False)
dart_point_inside = cv2.pointPolygonTest(dart_contour, dart_point, False)
# 如果飞镖落点在轮廓内,则判定为相应得分
if empty_point_inside >= 0 and dart_point_inside >= 0:
score = i + 1 # 得分从1开始计算
break
print("飞镖得分:", score)
需要注意的是,上述代码假设飞镖盘的得分区域已经提前分割好了,并且飞镖盘在图像中的位置已知。如果飞镖盘在图中不一定是正圆,可以使用图像处理的方法进行圆检测,然后再将得分区域分割出来
原文地址: http://www.cveoy.top/t/topic/h7Fu 著作权归作者所有。请勿转载和采集!