1import cv2
2
3cam = cv2.VideoCapture(0)
4
5cv2.namedWindow("test")
6
7img_counter = 0
8
9while True:
10 ret, frame = cam.read()
11 if not ret:
12 print("failed to grab frame")
13 break
14 cv2.imshow("test", frame)
15
16 k = cv2.waitKey(1)
17 if k%256 == 27:
18 # ESC pressed
19 print("Escape hit, closing...")
20 break
21 elif k%256 == 32:
22 # SPACE pressed
23 img_name = "opencv_frame_{}.png".format(img_counter)
24 cv2.imwrite(img_name, frame)
25 print("{} written!".format(img_name))
26 img_counter += 1
27
28cam.release()
29
30cv2.destroyAllWindows()
31