How to manually stop video recording?

asked 2017-05-08 11:40:21 -0500

batman_rising gravatar image

Hey guys, I am new to the world of programming, I am not from the computer science background. Currently, I am working on a project in which I am using raspberry pi 3 and a USB webcam (I am not using the Pi camera). My objective is to record a video using the webcam, I have interfaced a button switch with one of the GPIO pins, so if I press the push button once it should start recording the video and on the next press, it must stop recording. I used the example code to check whether I am able to record the video or not? I run the code using terminal and yes it works, but whenever I want to stop recording I have to press Ctrl+C, which terminates the entire process, I also want to execute some different operation once the video stops, but I have no idea how to do that. Please I need your guidance.

import numpy as np
import cv2
cap = cv2.VideoCapture(0)   #defining the webcam
fourcc =*'XVID')
out = cv2.VideoWriter('webcamOut.avi',fourcc,30.0,(640,480))

while True:
    ret, frame =
    if cv2.waitKey(1) & 0xFF ==ord('q'):


Also, one more thing. If I set the resolution higher than 480 (i.e. 720 or 1080), the output video saved with 5kb file size. what to do in that case? thanks

edit retag flag offensive close merge delete


your code clearly shows, that it will stop both capturing & recording, once you press the "q" key (in the gui window) , you probably did not notice it yet.

you could easily insert some code just before cap.release()

if you want to do the same using gpio pins, you'll have to insert some logic for that into the while loop, unfortunately, this is totally off-topic, we can't help you with that.

berak gravatar imageberak ( 2017-05-08 11:45:18 -0500 )edit