opencv鼠标选择roi区域
时间: 2023-07-07 21:18:30 浏览: 181
您好!要使用OpenCV选择ROI区域,可以使用鼠标回调函数和OpenCV提供的ROI选择函数。下面是一个基本的示例代码:
```python
import cv2
# 创建鼠标回调函数
def select_roi(event, x, y, flags, param):
global roi, roi_selected, start_x, start_y, end_x, end_y
if event == cv2.EVENT_LBUTTONDOWN:
roi_selected = False
start_x, start_y = x, y
elif event == cv2.EVENT_MOUSEMOVE:
if flags == cv2.EVENT_FLAG_LBUTTON:
img_copy = img.copy()
cv2.rectangle(img_copy, (start_x, start_y), (x, y), (0, 255, 0), 2)
cv2.imshow("image", img_copy)
elif event == cv2.EVENT_LBUTTONUP:
end_x, end_y = x, y
roi = img[start_y:end_y, start_x:end_x]
roi_selected = True
cv2.destroyAllWindows()
# 读取图像
img = cv2.imread("image.jpg")
# 创建窗口并绑定鼠标回调函数
cv2.namedWindow("image")
cv2.setMouseCallback("image", select_roi)
# 显示图像并等待选择ROI
while True:
cv2.imshow("image", img)
key = cv2.waitKey(1) & 0xFF
if roi_selected:
break
# 显示选择的ROI
cv2.imshow("ROI", roi)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
该代码可以打开一张图像,然后通过鼠标拖拽选择ROI区域,并显示选择的ROI。您可以根据需要修改代码以适应您的应用场景。
阅读全文