opencv 画矩形roi截图
时间: 2023-05-09 19:01:15 浏览: 96
OpenCV是一个开源的计算机视觉库。它提供了许多处理数字图像和视频的函数,而其中之一就是画矩形ROI截图。
首先,要创建一个矩形ROI,需要知道需要截取的区域的左上角和右下角的坐标。可以使用OpenCV自带的鼠标事件函数,在图像上拖动鼠标选择需要截取的区域并获取该区域的坐标。
其次,使用cv2.rectangle函数将矩形绘制在图像上。函数参数包括:原始图像,矩形左上角坐标,矩形右下角坐标,颜色和线宽度。
最后,使用numpy的切片操作截取原始图像中的ROI区域。切片的参数是左上角和右下角坐标,保持一致性。
示例程序如下:
```python
import cv2
import numpy as np
# Mouse callback function
def draw_rect(event, x, y, flags, params):
global x_init, y_init, drawing, top_left_pt, bottom_right_pt
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
x_init, y_init = x, y
elif event == cv2.EVENT_MOUSEMOVE:
if drawing:
top_left_pt = (min(x_init, x), min(y_init, y))
bottom_right_pt = (max(x_init, x), max(y_init, y))
img[y_init:y, x_init:x] = 255 - img[y_init:y, x_init:x]
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
top_left_pt = (min(x_init, x), min(y_init, y))
bottom_right_pt = (max(x_init, x), max(y_init, y))
img[y_init:y, x_init:x] = 255 - img[y_init:y, x_init:x]
# MAIN SCRIPT
drawing = False
top_left_pt, bottom_right_pt = (-1, -1), (-1, -1)
# Open image
img = cv2.imread('test.png')
copy = img.copy()
# Create a window
cv2.namedWindow("Window")
# Set the mouse callback function to "draw_rect"
cv2.setMouseCallback("Window", draw_rect)
while True:
cv2.imshow("Window", img)
k = cv2.waitKey(1) & 0xFF
# If "c" is pressed, reset the window
if k == ord('c'):
img = copy.copy()
# If "r" is pressed, crop the ROI
elif k == ord('r'):
if top_left_pt != (-1, -1) and bottom_right_pt != (-1, -1):
roi = copy[top_left_pt[1]:bottom_right_pt[1], top_left_pt[0]:bottom_right_pt[0]]
cv2.imshow("ROI", roi)
# If "q" is pressed, exit
elif k == ord('q'):
break
cv2.destroyAllWindows()
```
该程序允许用户在图像上拖动鼠标选择需要截取的区域。在选择完区域后,按下“r”键就可以截取该区域并显示在一个新窗口中。按下“c”键可以重置窗口。如果想要结束程序,按下“q”键即可。
阅读全文