Windows操作系统交互时出现cv2.VideoCapture问题

时间:2018-08-12 19:32:52

标签: python python-3.x video-capture opencv3.0 pyhook

我正在尝试编写python代码,每当我单击鼠标左键时,它们都会捕获并保存来自网络摄像头的图像。下面的代码以令人讨厌的怪癖实现了此功能;当它运行时,我的鼠标单击似乎不再与Windows交互(任务管理器除外)。

我希望能够在计算机上执行正常任务时在后台运行此代码(我正在为机器学习项目构建数据集),因此无法与Windows进行交互交易中断。

谁能告诉我为什么会这样和/或提供解决方法?

视频:https://youtu.be/ot_qA3fickw

以下代码:

import cv2
import time
def OnMouseClick(event):
    if event.MessageName=='mouse left down':
        #take a shot of the webcam on left mouse click and save
        global cap
        for i in range(4): #primitively clear camera buffer
            ret, frame=cap.read()

        log_file='test.csv'
        filename=time.strftime("%Y-%m-%d %H%M%S", time.gmtime()) + ".png"
        fob=open(log_file, 'a') 

        #save click location, image filename to CSV file
        fob.write(str(event.Position[0]))
        fob.write(', ')
        fob.write(str(event.Position[1]))
        fob.write(', ')
        fob.write(filename)
        fob.write('\n')

        #save the webcam image itself
        cv2.imwrite('./camera shots/' + filename, frame)
        print ('click')

    if event.MessageName=='mouse middle down':
        #breaks the main while: loop below on middle button press
        print('q')
        global q        
        q=True

    return False




if __name__ == '__main__':    
    import pythoncom
    #start the session#instantiate HookManager class
    hm=pyHook.HookManager()
    #listen to all button presses
    hm.MouseAllButtonsDown=OnMouseClick
    #hook the mouse
    hm.HookMouse()
    q=False     

    cap=cv2.VideoCapture(0)
    while q==False:
        pythoncom.PumpWaitingMessages()


    cap.release()
    hm.UnhookMouse()

0 个答案:

没有答案