Получить ширину изображения камеры в OpenCV

В OpenCV ширину изображения камеры можно получить различными методами. Вот несколько способов добиться этого:

Метод 1: использование свойства cv2.CAP_PROP_FRAME_WIDTH

import cv2
cap = cv2.VideoCapture(0)  # Open the default camera
# Read a frame to get the width
ret, frame = cap.read()
if ret:
    width = frame.shape[1]
    print("Image width:", width)
cap.release()  # Release the camera

Метод 2: доступ к свойству shapeкадра

import cv2
cap = cv2.VideoCapture(0)  # Open the default camera
# Read a frame to get the width
ret, frame = cap.read()
if ret:
    height, width, _ = frame.shape
    print("Image width:", width)
cap.release()  # Release the camera

Метод 3: запрос свойства CV_CAP_PROP_FRAME_WIDTH

import cv2
cap = cv2.VideoCapture(0)  # Open the default camera
# Get the width property
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
print("Image width:", width)
cap.release()  # Release the camera

Метод 4: использование свойства cv2.CAP_PROP_FRAME_WIDTHс определенным индексом камеры

import cv2
cap = cv2.VideoCapture(1)  # Open a specific camera (index 1)
# Get the width property
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
print("Image width:", width)
cap.release()  # Release the camera

Метод 5. Установка предварительно заданной ширины и высоты изображения с камеры

import cv2
cap = cv2.VideoCapture(0)  # Open the default camera
# Set a predefined width and height
width = 640  # Specify the desired width
height = 480  # Specify the desired height
cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
print("Image width:", width)
cap.release()  # Release the camera