Frage

How to give start, stop, capture, and close buttons in video capture window to start, to stop, to take snapshot, to close the window?

I am using the below code to to open camera for video streaming:

import cv2.cv as cv
    cv.NamedWindow("camera", 1)
    capture = cv.CaptureFromCAM(0)
    while True:
        img = cv.QueryFrame(capture)
        cv.ShowImage("camera", img)
        if cv.WaitKey(10) == 27:
            break
War es hilfreich?

Lösung

Buttons aren't possible but you can use mouse clicks and key strokes to control your video. For example, use left click to toggle play/pause and implement record via key stroke:

import cv2

run=False
frame=0
path=#some video path

def foo(event, x, y, flags, param):
    global run
    global frame
    #check which mouse button was pressed
    #e.g. play video on left mouse click
    if event == cv2.EVENT_LBUTTONDOWN:
        run= not run
        while run:

            frame+=1
            frame=cap.read()[1]
            cv2.imshow(window_name, frame)
            key = cv2.waitKey(5) & 0xFF
            if key == ord("v"):
                pass
                #do some stuff on key press

    elif event == cv2.EVENT_RBUTTONDOWN:
        pass
        #do some other stuff on right click


window_name='videoPlayer'
cv2.namedWindow(window_name)
cv2.setMouseCallback(window_name, foo)

cap=cv2.VideoCapture(path)

Andere Tipps

I had this problem before with OpenCV. As far as I am aware there is no functionality for buttons in OpenCV.

However, I used Tkinter and created a canvas along with some buttons (in your case these will be start, stop, capture, close). Each frame that was captured using OpenCV I drew onto the Tkinter canvas.

I was using this for a frame by frame program, so I am not sure how well this method will perform in real time.

A very quick example code:

from Tkinter import *
import cv2.cv as cv

root = Tk()

w = Canvas(root, width=500, height=300, bd = 10, bg = 'white')
w.grid(row = 0, column = 0, columnspan = 2)

b = Button(width = 10, height = 2, text = 'Button1')
b.grid(row = 1, column = 0)
b2 = Button(width = 10, height = 2, text = 'Button2')
b2.grid(row = 1,column = 1)

cv.NamedWindow("camera",1)
capture = cv.CaptureFromCAM(0)

while True:
    img = cv.QueryFrame(capture)
    canvas.create_image(0,0, image=img)
    if cv.WaitKey(10) == 27:
        break

root.mainloop()

This may or may not work right off the bat as I am not in a position to test this right now. One potential change I can see would be the image format OpenCV uses. You may need to use one of the conversion functions to change the format.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top