This is a commentary for those who want to use the camera with Python. This is an article for beginners that explains how to acquire camera images and save images and videos.
macOS Catalina 10.15.4 Python 3.7.5 opencv-python 4.2.0.34 numpy 1.18.2
$ pip install opencv-python
numpy will be installed as soon as you install opencv-python
import cv2
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
cv2.imshow('frame', frame)
if cv2.waitKey(1) == ord('q'):
break
cv2.destroyAllWindows()
cap.release()
Specify the camera number with the argument of cv2.VideoCapture (). 0 is assigned when using the built-in camera such as a laptop computer or when only one camera is connected. Press q on your keyboard to exit.
import cv2
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
cv2.imshow('frame', frame)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
elif key == ord('c'):
cv2.imwrite('image.jpg', frame)
cv2.destroyAllWindows()
cap.release()
Specify the path to save the image (either absolute path or relative path) in the first argument of cv2.imwrite (). Save current frame with c on keyboard
import cv2
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
fps = cap.get(cv2.CAP_PROP_FPS)
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
video = cv2.VideoWriter('video.mp4', fourcc, fps, size)
while True:
ret, frame = cap.read()
video.write(frame)
cv2.imshow('frame', frame)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
cv2.destroyAllWindows()
video.release()
cap.release()
Save the video from running the program to pressing q on the keyboard. The save destination of the video can be specified by the first argument of cv2.VideoWriter ().
This time, I introduced how to use OpenCV easily. If I have another chance, I would like to introduce face recognition using OpenCV.
Recommended Posts