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

Problems while Cropping ROI with mouse using Open CV

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

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

  2. 绘制的矩形个数this, though the cropping works fine.

这是代码

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 解决方案:

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