python - 在窗口上创建捕获按钮

标签 python opencv

我有这个代码可以打开相机显示视频。

cap = cv2.VideoCapture(0)
while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

正如您在上面的代码中看到的,我使用 cv2.imshow 函数来显示视频。

我需要创建按钮来捕获视频。

我的问题是可以在由 cv2.imshow 函数创建的窗口内创建按钮吗?

最佳答案

评论提供了很好的选项、键绑定(bind)和/或 tkinter。如果您确实想要一个可视化界面,但不想使用 tkinter,您可以使用以下“技巧”之一:

  • OpenCV 确实支持 slider ,因此您可以使用范围为 1 的 slider 来构建开/关界面。
  • 在单独的窗口中显示按钮的图像。添加鼠标回调,并检查鼠标点击是否在“按钮”的尺寸范围内。

  • 您甚至可以将两者结合在一个控制面板中:
    enter image description here

    代码:
    import cv2
    import numpy as np 
    
    # button dimensions (y1,y2,x1,x2)
    button = [20,60,50,250]
    
    # function that handles the mousclicks
    def process_click(event, x, y,flags, params):
        # check if the click is within the dimensions of the button
        if event == cv2.EVENT_LBUTTONDOWN:
            if y > button[0] and y < button[1] and x > button[2] and x < button[3]:   
                print('Clicked on Button!')
    
    # function that handles the trackbar
    def startCapture(val):
        # check if the value of the slider 
        if val == 1:
            print('Capture started!')
        else:
            print('Capture stopped!')            
    
    # create a window and attach a mousecallback and a trackbar
    cv2.namedWindow('Control')
    cv2.setMouseCallback('Control',process_click)
    cv2.createTrackbar("Capture", 'Control', 0,1, startCapture)
    
    # create button image
    control_image = np.zeros((80,300), np.uint8)
    control_image[button[0]:button[1],button[2]:button[3]] = 180
    cv2.putText(control_image, 'Button',(100,50),cv2.FONT_HERSHEY_PLAIN, 2,(0),3)
    
    #show 'control panel'
    cv2.imshow('Control', control_image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    关于python - 在窗口上创建捕获按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55919337/

    相关文章:

    python - Django 仅对新条目发出信号

    Python Popen 输出到 C 程序,fget 在循环中读取相同的 stdin

    python - 如何不通过大写其他代码来替换代码?

    android - 如何在Android中使用OpenCV以编程方式播放视频?

    带有 Visual Studio 2015 的 OpenCV(msvcr120d.dll 错误)

    Android [opencv]裁剪板

    python - 在我的 Raspberry PI 上使用 Python 和 OpenCV 没有保存视频文件

    python - 使用 numpy 的加权百分位数

    opencv - 将具有简单形状的图像转换为多边形

    c++ - OpenCV 从 Mat 访问元素