Simple Code
import cv2
import numpy as np
cap = cv2.VideoCapture(-1)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
frame = cv2.flip(frame, 1)
# Display the resulting frame
cv2.imshow('frame',frame)
print(frame.shape)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
Description:
The 1st 2 lines import the required packages numpy and opencv. These should already be installed
Line 3 sets up the stream from the camera. Depending on which USB socket the webcam is on change the number ie -1,0,1,2 etc
The default frame size is 640 x480
While(True): is an infinite loop to test the camera connection.
ret, frame = cap.read() says that if a frame is received from the stream named 'cap' asign it the name 'frame'
the next line flips the frame left to right. If you need to flip it up & down put a '0' here and if you want to flip it left & right & up & down put '-1'
cv2.imshow('Frame Window',frame) displays the frame on the screen in a window titled 'Frame Window'
print(frame.shape) prints the dimensions of the 'array' that represents the frame. The number 3 represents the 3 colours of the pixel (BGR).
Note that in opencv the 1st number is the y axis and the 2nd number is the x axis
if cv2.waitKey(1) & 0xFF == ord('q'): This means if the q key is pressed break out of the infinite loop. (the 0xFF just filters out any other data that might be in the key press)
When the 'q' key is pressed the last 2 lines close the display window and release the capture stream.
A more detailed 'Simple' example
import cv2
HIGH_VALUE = 10000
WIDTH = HIGH_VALUE
HEIGHT = HIGH_VALUE
capture = cv2.VideoCapture(-1)
capture.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))
capture.set(cv2.CAP_PROP_FRAME_WIDTH, WIDTH)
capture.set(cv2.CAP_PROP_FRAME_HEIGHT, HEIGHT)
width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = capture.get(cv2.CAP_PROP_FPS)
print(width, height, fps)
while True:
ret, frame = capture.read()
if ret:
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
capture.release()
cv2.destroyAllWindows()
Detailed