以下是一个使用 Python 和 OpenCV 库实现左键点击选取 ROI 点并显示 ROI 多边形,双击左键结束选择,同时显示原始图片和采集的 ROI 图像的示例代码: ```python import cv2 # 全局变量用于存储 ROI 点 points = [] drawing = False def draw_roi(event, x, y, flags, param): global points, drawing if event == cv2.EVENT_LBUTTONDOWN: drawing = True points.append((x, y)) elif event == cv2.EVENT_LBUTTONUP: drawing = False elif event == cv2.EVENT_MOUSEMOVE and drawing: points.append((x, y)) # 读取原始图像 img = cv2.imread('your_image.jpg') cv2.namedWindow('image') cv2.setMouseCallback('image', draw_roi) while True: temp_img = img.copy() if len(points) > 0: cv2.polylines(temp_img, [np.array(points)], isClosed=False, color=(0, 255, 0), thickness=2) cv2.imshow('image', temp_img) key = cv2.waitKey(1) & 0xFF if key == 27: # 按下 Esc 键退出 break elif key == 13: # 双击左键(回车键)结束选择 if len(points) >= 3: roi_mask = np.zeros(img.shape[:2], dtype=np.uint8) cv2.fillPoly(roi_mask, [np.array(points)], 255) roi_img = cv2.bitwise_and(img, img, mask=roi_mask) cv2.imshow('ROI Image', roi_img) cv2.waitKey(0) cv2.destroyWindow('ROI Image') points = [] cv2.destroyAllWindows() ``` 在上述代码中,首先读取原始图像。通过鼠标事件函数`draw_roi`记录左键点击的坐标点。当双击左键(回车键)时,根据记录的点生成 ROI 并显示 ROI 图像。 请将`'your_image.jpg'`替换为您实际的图像路径。运行代码后,在图像窗口中通过左键点击选取 ROI 点,双击左键结束选择。 [2024-11-09 13:23:27 | AI写代码神器 | 531点数解答]