Monday, August 14, 2023

OpenCV basics continued...Display Webcam

Like displaying videos, a similar technique is used to display webcam. Replace the above Line 6 with cap = cv2.VideoCapture(0), it will load the laptop/desktop’s default webcam and display it.

In the previous post the parameter of cv2.VideoCapture() function was the path of the video file, now pass the index of the webcam device as parameter, here 0 is used as the default webcam, it will connect to the default webcam.

Some video properties can also be set here, as below-

1 import cv2

2

3

cap = cv2.VideoCapture(0)

# read from default webcam

4

5 # Set video properties

6

cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)

# set width

7

cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

# set height

8

cap.set(cv2.CAP_PROP_BRIGHTNESS, 180)

# set brightness

9

cap.set(cv2.CAP_PROP_CONTRAST, 50)

# set contrast

10

11 success, img = cap.read()

12 while success:

13 cv2.imshow("Webcam", img)

14

15 # Press ESC key to break the loop

16 if cv2.waitKey(10) & 0xFF == 27:

17 break

18 success, img = cap.read()

19

20 cap.release()

21 cv2.destroyWindow("Webcam")

Line 3 Load video from default Webcam.

Line 6 Set width of the camera video.

Line 7 Set height of the camera video.

Line 8 Set brightness of the camera video.

Line 9 Set contrast of the camera video.

For references, this is the list that can be used as parameter for cap.set():

0 CAP_PROP_POS_MSEC Current position of the video file in milliseconds.

1 CAP_PROP_POS_FRAMES 0-based index of the frame to be decoded/captured next.

2 CAP_PROP_POS_AVI_RATIO Relative position of the video file

3 CAP_PROP_FRAME_WIDTH Width of the frames in the video stream.

4 CAP_PROP_FRAME_HEIGHT Height of the frames in the video stream.

5 CAP_PROP_FPS Frame rate.

6 CAP_PROP_FOURCC 4-character code of codec.

7 CAP_PROP_FRAME_COUNT Number of frames in the video file.

8 CAP_PROP_FORMAT Format of the Mat objects returned by retrieve() .

9 CAP_PROP_MODE Backend-specific value indicating the current capture mode.

10 CAP_PROP_BRIGHTNESS Brightness of the image (only for cameras).

11 CAP_PROP_CONTRAST Contrast of the image (only for cameras).

12 CAP_PROP_SATURATION Saturation of the image (only for cameras).

13 CAP_PROP_HUE Hue of the image (only for cameras).

14 CAP_PROP_GAIN Gain of the image (only for cameras).

15 CAP_PROP_EXPOSURE Exposure (only for cameras).

16 CAP_PROP_CONVERT_RGB Boolean flags indicating whether images should be converted to RGB.

17 CAP_PROP_WHITE_BALANCE Currently unsupported

18 CAP_PROP_RECTIFICATION Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently)

Make sure a webcam is attached to the laptop/desktop computer and enabled, execute the code you will see a window displaying whatever the webcam captures. Press ESC key to terminate.

Share:

0 comments:

Post a Comment