使用Open CV使用鼠标裁剪ROI时出现的问题

时间:2018-02-23 05:10:37

标签: python opencv image-processing python-3.6 opencv3.0

以下是我面临的两个问题:

  1. 仅当鼠标从左上角拖动到右下角时,裁剪才有效。

  2. 绘制的矩形数量与this类似,但裁剪有效fine

  3. 这是代码

    import cv2
    import numpy as np
    
    cropping = False
    x_start, y_start, x_end, y_end = 0, 0, 0, 0
    
    def mouse_crop(event, x, y, flags, param):
        global x_start, y_start, x_end, y_end, cropping,refPoint
    
        if event == cv2.EVENT_LBUTTONDOWN:
            x_start, y_start, x_end, y_end = x, y, x, y
            cropping = True
        elif event == cv2.EVENT_MOUSEMOVE:
            if cropping == True:
                x_end, y_end = x, y
        elif event == cv2.EVENT_LBUTTONUP:
            x_end, y_end = x, y
            cropping = False 
            refPoint = [(x_start, y_start), (x_end, y_end)]
    
    image = cv2.imread('orig.jpg')
    oriImage = image.copy()
    cv2.namedWindow("image")
    cv2.setMouseCallback("image", mouse_crop)
    
    while True:
        if not cropping:
            cv2.imshow("image", image)
        elif cropping:
             cv2.rectangle(image, (x_start, y_start), (x_end, y_end), (255, 0, 0), 2)
        cv2.imshow("image", image) 
        key = cv2.waitKey(1) & 0xFF
        if key == (27):
            image = oriImage.copy()
        elif key == (13):
            break
    if len(refPoint) == 2:
        roi = oriImage[refPoint[0][1]:refPoint[1][1], refPoint[0][0]:refPoint[1][0]]
        cv2.imshow("Cropped", roi)
        cv2.waitKey(0)
    
    cv2.destroyAllWindows()
    

1 个答案:

答案 0 :(得分:0)

问题1解决方案:

if len(refPoint) == 2:
    print(refPoint[0][0],refPoint[0][1],refPoint[1][0],refPoint[1][1])
    x_s = refPoint[0][0]
    y_s = refPoint[0][1]
    x_e = refPoint[1][0]
    y_e = refPoint[1][1]
    x_big, x_small = ((x_s, x_e) if x_s>x_e else (x_e, x_s))
    y_big, y_small = ((y_s, y_e) if y_s>y_e else (y_e, y_s))
    roi = oriImage[y_small:y_big, x_small:x_big]          
    cv2.imshow("Cropped", roi)
    cv2.waitKey(0)

问题2解决方案:只需添加以下行:image = oriImage.copy(),如下所示:

while True:
if not cropping:
    cv2.imshow("image", image)
elif cropping:
    image = oriImage.copy()
    cv2.rectangle(image, (x_start, y_start), (x_end, y_end), (255, 0, 0), 2)
cv2.imshow("image", image) 
key = cv2.waitKey(1) & 0xFF
if key == (27):
    image = oriImage.copy()
elif key == (13):
    break