opencv 感兴趣区域提取 (ROI)

opencv 感兴趣区域提取 (ROI)

  • 1)使用像素坐标来提取ROI,前提是知道感兴趣区域的具体坐标范围
def img_cut():
     os.chdir(input)
    img_row = 1
     for image_name in os.listdir(os.getcwd()):
        print(image_name)
        img_row=img_row+1
        im = cv2.imread(os.path.join(input, image_name))
        if (im is None):
            print('读取照片失败')
            return -1
        im=im[600:1057,0:600]   # 裁剪坐标为[y0:y1, x0:x1]
        cv2.waitKey(0) #等待输入再关闭窗口
        cv2.imwrite((os.path.join(output, image_name)),im)

opencv 感兴趣区域提取 (ROI)_第1张图片

opencv 感兴趣区域提取 (ROI)_第2张图片

  • 2)使用鼠标选择想要的感兴趣区域(引用)
import cv2
global img
global point1, point2
def on_mouse(event, x, y, flags, param):
    global img, point1, point2
    img2 = img.copy()
    if event == cv2.EVENT_LBUTTONDOWN:  # 左键点击
        point1 = (x, y)
        cv2.circle(img2, point1, 10, (0, 255, 0), 5)
        cv2.imshow('src', img2)
    elif event == cv2.EVENT_MOUSEMOVE and (flags & cv2.EVENT_FLAG_LBUTTON):  # 按住左键拖曳
        cv2.rectangle(img2, point1, (x, y), (255, 0, 0), 5)
        cv2.imshow('src', img2)
    elif event == cv2.EVENT_LBUTTONUP:  # 左键释放
        point2 = (x, y)
        cv2.rectangle(img2, point1, point2, (0, 0, 255), 5)
        cv2.imshow('src', img2)
        min_x = min(point1[0], point2[0])
        min_y = min(point1[1], point2[1])
        width = abs(point1[0] - point2[0])
        height = abs(point1[1] - point2[1])
        cut_img = img[min_y:min_y + height, min_x:min_x + width]
        cv2.imshow('ROI_rectangle', cut_img)
        cv2.destroyWindow('ROI_rectangle')
def main():
    global img
    img = cv2.imread('g0001.jpg')
    cv2.namedWindow('src')
    cv2.setMouseCallback('src', on_mouse)
    cv2.imshow('src', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
if __name__ == '__main__':
    main()```
 

你可能感兴趣的:(opencv,计算机视觉,cv)