OpenCV (Python)
Display live full resolution video from USB camera
OpenCV can grab video frames directly from USB camera. However it can be tricky to get full resolution and MJPEG compression. Example below unlocks full capabilities and captures 1080p@30fps from C1 family cameras.
More detailed bog post about OpenCV tricks to get full resolution from USB camera.
Code #1
import cv2
camera = cv2.VideoCapture(0, cv2.CAP_DSHOW)
camera.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
camera.set(cv2.CAP_PROP_FPS, 30.0)
camera.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter.fourcc('m','j','p','g'))
camera.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter.fourcc('M','J','P','G'))
while (1):
retval, im = camera.read()
cv2.imshow("image", im)
k = cv2.waitKey(1) & 0xff
if k == 27:
break
camera.release()
cv2.destroyAllWindows()
Versions
Python (Windows) | 3.8.4rc1 |
OpenCV |
4.3.0 |
Code #2
import cv2
print("Initializing camera")
camera = cv2.VideoCapture(0, cv2.CAP_DSHOW)
print("Setting camera mode")
camera.set(cv2.CAP_PROP_FPS, 30.0)
camera.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter.fourcc('m','j','p','g'))
camera.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter.fourcc('M','J','P','G'))
camera.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
print("Starting capture")
while(1):
retval, im = camera.read()
scale = 0.5
im = cv2.resize(im, None, fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC)
cv2.imshow("image", im)
camera.set(cv2.CAP_PROP_EXPOSURE, -10)
camera.set(cv2.CAP_PROP_GAIN, 30)
k = cv2.waitKey(1) & 0xff
if k == 27:
print("exit")
break
camera.release()
cv2.destroyAllWindows()
Versions
Python (Windows) | 3.10.0 |
OpenCV |
4.9.0 |