How to access an external webcam using OpenCV?

In order to access an external camera, you first need to install the OpenCV library and set up your development environment. Then, you can follow these steps to call the external camera:

  1. Import the OpenCV library.
import cv2
  1. Create a VideoCapture object to connect to the camera.
cap = cv2.VideoCapture(0)  # 参数0表示连接第一个摄像头
  1. Read each frame of the camera in a loop.
while True:
    ret, frame = cap.read()  # 读取一帧图像
    cv2.imshow('Frame', frame)  # 显示当前帧图像

    if cv2.waitKey(1) & 0xFF == ord('q'):  # 按下'q'键退出循环
        break
  1. Release the camera resources and close the window.
cap.release()
cv2.destroyAllWindows()

Complete code example:

import cv2

cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    cv2.imshow('Frame', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

When the code is running, a window will open displaying the image captured by the camera. Pressing the ‘q’ key can exit the program.

bannerAds