How to Capture Frames from Camera with OpenCV in Python

From RidgeRun Developer Wiki

Introduction

OpenCV is a library of programming functions mainly aimed at real-time computer vision. It is widely used to capture images from cameras, do some processing, and then play it back or save it. The following wiki includes a small sample program in Python to capture frames from camera.

Dependencies

  • Python
  • OpenCV >= 3.0
  • v4l-ctl

Video Device Information

1. Get the ID of the camera to be used

ls /dev/video*

You may get several video entries depending on the number of video devices that are connected

/dev/video0  /dev/video1

2. Choose the video device and verify formats

Install required tool

sudo apt install v4l-utils

Run the following command to get available image formats

v4l2-ctl --device /dev/video0 --list-formats-ext

You will get a results with supported formats by video source

ioctl: VIDIOC_ENUM_FMT
	Index       : 0
	Type        : Video Capture
	Pixel Format: 'MJPG' (compressed)
	Name        : Motion-JPEG
		Size: Discrete 1920x1080
			Interval: Discrete 0.033s (30.000 fps)
		Size: Discrete 1280x720
			Interval: Discrete 0.017s (60.000 fps)
		Size: Discrete 1024x768
			Interval: Discrete 0.033s (30.000 fps)
		Size: Discrete 640x480
			Interval: Discrete 0.008s (120.101 fps)
		Size: Discrete 800x600
			Interval: Discrete 0.017s (60.000 fps)
		Size: Discrete 1280x1024
			Interval: Discrete 0.033s (30.000 fps)
		Size: Discrete 320x240
			Interval: Discrete 0.008s (120.101 fps)

	Index       : 1
	Type        : Video Capture
	Pixel Format: 'YUYV'
	Name        : YUYV 4:2:2
		Size: Discrete 1920x1080
			Interval: Discrete 0.167s (6.000 fps)
		Size: Discrete 1280x720
			Interval: Discrete 0.111s (9.000 fps)
		Size: Discrete 1024x768
			Interval: Discrete 0.167s (6.000 fps)
		Size: Discrete 640x480
			Interval: Discrete 0.033s (30.000 fps)
		Size: Discrete 800x600
			Interval: Discrete 0.050s (20.000 fps)
		Size: Discrete 1280x1024
			Interval: Discrete 0.167s (6.000 fps)
		Size: Discrete 320x240
			Interval: Discrete 0.033s (30.000 fps)


Example

With the information obtained from the previous section you can use the video device ID and the video format and resolution.

import cv2

# Open the device at the ID 0
# Use the camera ID based on
# /dev/videoID needed
cap = cv2.VideoCapture(0)

#Check if camera was opened correctly
if not (cap.isOpened()):
    print("Could not open video device")


#Set the resolution
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)

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

    # Display the resulting frame
    
    cv2.imshow("preview",frame)
    
    cv2.imwrite("outputImage.jpg", frame)

    #Waits for a user input to quit the application
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

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