Let's Take Picture
# Import Computer Vision package - cv2
import cv2
import numpy as np
webcam = cv2.VideoCapture(0)
ret, frame = webcam.read()
print (ret)
webcam.release()
True
How to show it?
cv2.imshow("my image", frame)
cv2.waitKey()
cv2.destroyAllWindows()
Getting Started with Videos
Ø Capture Video from Camera
To capture a video, you need to create a VideoCapture object. Its argument can be either the device index or the name of a video file. Device index is just the number to specify which camera. Normally one camera will be connected (as in my case). So I simply pass 0 (or -1). You can select the second camera by passing 1 and so on. After that, you can capture frame-by-frame. But at the end, don’t forget to release the capture.
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while(True):
#capture frame-by-frame
ret, frame = cap.read()
#our operations on the frame came here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#display the resulting frame
cv2.imshow("goeduhub", gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#when everything done release the capture
cap.release()
cv2.destroyAllWindows()
· cap.read() returns a bool (True/False). If frame is read correctly, it will be True. So you can check end of the video by checking this return value.
· You can end the video by pressing ‘q’.
Ø Playing Video from File
It is same as capturing from Camera, just change camera index with video file name. Also while displaying the frame, use appropriate time for cv2.waitKey(). If it is too less, video will be very fast and if it is too high, video will be slow (Well, that is how you can display videos in slow motion). 25 milliseconds will be OK in normal cases.
import cv2
import numpy as np
cap = cv2.VideoCapture('vtest.avi')
while(cap.isOpened()):
ret, frame = cap.read()
#our operations on the frame came here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#display the resulting frame
cv2.imshow("goeduhub", gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#when everything done release the capture
cap.release()
cv2.destroyAllWindows()