Python OpenCV : mouse callback for drawing rectangle

标签 python opencv mouseevent draw

我想从视频流中保存一张图像,然后在显示的图像上绘制一个矩形以生成感兴趣的区域。稍后,将该 ROI 保存在一个文件中。我使用 opencv python grabcut 示例来使用 setMouseCallback 函数。但我不知道我做错了什么,因为它没有给出我期望的结果。我希望看到在 mouse input 窗口中显示的静态图像上绘制的绿色矩形,并将 roi 保存到文件中。请帮助调试此代码或展示更好的方法:

import cv2

rect = (0,0,1,1)
rectangle = False
rect_over = False  
def onmouse(event,x,y,flags,params):
    global sceneImg,rectangle,rect,ix,iy,rect_over

    # Draw Rectangle
    if event == cv2.EVENT_LBUTTONDOWN:
        rectangle = True
        ix,iy = x,y

    elif event == cv2.EVENT_MOUSEMOVE:
        if rectangle == True:
            cv2.rectangle(sceneImg,(ix,iy),(x,y),(0,255,0),2)
            rect = (min(ix,x),min(iy,y),abs(ix-x),abs(iy-y))

    elif event == cv2.EVENT_LBUTTONUP:
        rectangle = False
        rect_over = True
        cv2.rectangle(sceneImg,(ix,iy),(x,y),(0,255,0),2)
        rect = (min(ix,x),min(iy,y),abs(ix-x),abs(iy-y))

        x1,y1,w,h = rect        
        roi = sceneImg[y1:y1+h, x1:x1+w]

        cv2.imwrite('roi.jpg', roi)

# Named window and mouse callback
cv2.namedWindow('video')
cv2.namedWindow('mouse input')
cv2.setMouseCallback('mouse input',onmouse)

camObj = cv2.VideoCapture(-1)
keyPressed = None
running = True
scene = False
# Start video stream
while running:
    readOK, frame = camObj.read()

    keyPressed = cv2.waitKey(5)
    if keyPressed == ord('s'):
        scene = True

        cv2.imwrite('sceneImg.jpg',frame)
        sceneImg = cv2.imread('sceneImg.jpg')

        cv2.destroyWindow('video')
        cv2.imshow('mouse input', sceneImg)

    elif keyPressed == ord('r'):
        scene = False
        cv2.destroyWindow('mouse input')

    elif keyPressed == ord('q'):
        running = False

    if not scene:
        cv2.imshow('video', frame)

cv2.destroyAllWindows()
camObj.release()

最佳答案

每次调用 {event == cv2.EVENT_MOUSEMOVE:} 时,您都需要重置图像。

您的代码应如下所示:

if event == cv2.EVENT_LBUTTONDOWN:
    rectangle = True
    ix,iy = x,y

elif event == cv2.EVENT_MOUSEMOVE:
    if rectangle == True:
        sceneImg = sceneImg2.copy()
        cv2.rectangle(sceneImg,(ix,iy),(x,y),(0,255,0),2)
        rect = (min(ix,x),min(iy,y),abs(ix-x),abs(iy-y))


elif event == cv2.EVENT_LBUTTONUP:
    rectangle = False
    rect_over = True

    cv2.rectangle(sceneImg,(ix,iy),(x,y),(0,255,0),2)
    rect = (min(ix,x),min(iy,y),abs(ix-x),abs(iy-y))

关于Python OpenCV : mouse callback for drawing rectangle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28823243/

相关文章:

python - 如何从 Pandas 数据框函数调用中回顾前几行?

python - (django)根据用户的兴趣显示帖子

android - 如何解决以非零退出值2/退出值-1完成的 “Android/Sdk/ndk-bundle/ndk-build.cmd”

javascript - 在 ipad 上触发 unhover/mouseout/blur

java - 使用 FillLayout 在 Composite 上记录 SWT MouseEnter/Exit 事件

python - Python中有定时执行器服务吗?

python - 查找上个月

python - 使用 Python OpenCV cv2.VideoCapture() 直接读取灰度视频帧

OpenCV 怪胎 : Fast Retina KeyPoint descriptor

javascript - 如何使用 jQuery 在事件处理程序上获取文档,除了文档中的一个类?