酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

python使用opcv截取两张图片中间黄色圈然后对比计算出图片一比图片二总偏移百分比

以下是一个使用 OpenCV 库来解决此问题的示例代码框架,不过这个示例只是一个基本的指导,实际应用中可能需要根据图片的具体情况进行更多的调整和优化: ```python import cv2 def calculate_offset_percentage(image1, image2): # 将图像转换为 HSV 颜色空间 hsv_image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2HSV) hsv_image2 = cv2.cvtColor(image2, cv2.COLOR_BGR2HSV) # 定义黄色的 HSV 范围 lower_yellow = np.array([20, 100, 100]) upper_yellow = np.array([40, 255, 255]) # 提取黄色区域的掩码 mask1 = cv2.inRange(hsv_image1, lower_yellow, upper_yellow) mask2 = cv2.inRange(hsv_image2, lower_yellow, upper_yellow) # 找到黄色区域的轮廓 contours1, _ = cv2.findContours(mask1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contours2, _ = cv2.findContours(mask2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if len(contours1) > 0 and len(contours2) > 0: # 假设只处理最大的轮廓 contour1 = max(contours1, key=cv2.contourArea) contour2 = max(contours2, key=cv2.contourArea) # 计算轮廓的质心 M1 = cv2.moments(contour1) cx1, cy1 = int(M1['m10'] / M1['m00']), int(M1['m01'] / M1['m00']) M2 = cv2.moments(contour2) cx2, cy2 = int(M2['m10'] / M2['m00']), int(M2['m01'] / M2['m00']) # 计算偏移量 offset_x = cx2 - cx1 offset_y = cy2 - cy1 # 计算图像的宽度和高度 height, width = image1.shape[:2] # 计算总偏移百分比 total_offset = np.sqrt(offset_x 2 + offset_y 2) total_pixels = width * height offset_percentage = (total_offset / total_pixels) * 100 return offset_percentage else: return None # 读取两张图片 image1 = cv2.imread('image1.jpg') image2 = cv2.imread('image2.jpg') offset_percentage = calculate_offset_percentage(image1, image2) if offset_percentage is not None: print(f"总偏移百分比: {offset_percentage}%") else: print("未检测到黄色区域") ``` 在上述代码中,我们首先将图像转换为 HSV 颜色空间以更好地检测黄色区域。然后,通过掩码提取黄色区域,找到其轮廓,并计算轮廓的质心。根据质心的偏移量计算总偏移百分比。 您需要根据实际情况调整黄色的 HSV 范围以及处理可能出现的异常情况。 [2024-08-10 10:56:07 | AI写代码神器 | 786点数解答]

相关提问