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

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

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

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

  2. 绘制的矩形数量类似于 this , 尽管裁剪有效 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

关于python - 使用 Open CV 用鼠标裁剪 ROI 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48941504/

相关文章:

python - 为什么输入数组在递归函数内部发生变化?

python - MySQL INSERT 数据没有存储在正确的数据库中,只是临时存储的?

c++ - 查找图像中圆的各个中心点

c++ - 在 C::B 上使用 Borland 配置 OpenCV 2.2

python - 如何使用 PyMySQL 连接到数据库?

python - matplotlib 和 dateutil 的弃用警告

opencv从任意区域提取路径(中心线)

c - 如何从 LBP 图像中获取 256 个 bins/pixels?

html - 哪种图像扩展在质量和性能(速度)方面都更好?

c++ - 如何从椭圆图像中找到上下弧的长度