|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import cv2 |
| 4 | +import time |
| 5 | + |
| 6 | +# get the installed camera list for initialization. |
| 7 | +def get_cam_lst(cam_lst=range(0, 24)): |
| 8 | + arr = [] |
| 9 | + for iCam in cam_lst: |
| 10 | + cap = cv2.VideoCapture(iCam) |
| 11 | + if not cap.read()[0]: |
| 12 | + continue |
| 13 | + else: |
| 14 | + arr.append(iCam) |
| 15 | + |
| 16 | + cap.release() |
| 17 | + return arr |
| 18 | + |
| 19 | +def show_cam_img(caps, cam_list): |
| 20 | + print("INFO: Press 'q' to quit! Press 's' to save a picture, 'n' to change to next camera device!") |
| 21 | + idx = 0 |
| 22 | + while True: |
| 23 | + cap_device = caps[idx] |
| 24 | + ret, frame = cap_device.read() |
| 25 | + if ret: |
| 26 | + cv2.imshow('video', frame) |
| 27 | + else: |
| 28 | + print("ERROR: failed read frame!") |
| 29 | + |
| 30 | + # quit the test |
| 31 | + c = cv2.waitKey(1) |
| 32 | + if c == ord('q'): |
| 33 | + break |
| 34 | + |
| 35 | + # change to next camera device |
| 36 | + if c == ord('n'): |
| 37 | + idx += 1 |
| 38 | + if idx >= len(caps): |
| 39 | + idx = 0 |
| 40 | + continue |
| 41 | + |
| 42 | + # save the picture |
| 43 | + if c == ord('s'): |
| 44 | + if ret: |
| 45 | + name = 'video{0}_{1}.png'.format(cam_list[idx], |
| 46 | + time.strftime("%Y-%m-%d_%H:%M:%S", time.localtime())) |
| 47 | + cv2.imwrite(name, frame) |
| 48 | + print("saved file: %s!" %name) |
| 49 | + |
| 50 | + cv2.destroyAllWindows() |
| 51 | + |
| 52 | +def init_caps(cam_list, resolution=(1280,720)): |
| 53 | + caps = [] |
| 54 | + for iCam in cam_list: |
| 55 | + cap = cv2.VideoCapture(iCam) |
| 56 | + cap.set(3, resolution[0]) |
| 57 | + cap.set(4, resolution[1]) |
| 58 | + caps.append(cap) |
| 59 | + |
| 60 | + return caps |
| 61 | + |
| 62 | +def deinit_caps(cap_list): |
| 63 | + for cap in cap_list: |
| 64 | + cap.release() |
| 65 | + |
| 66 | +def show_cameras(video_list=None): |
| 67 | + if video_list == None: |
| 68 | + print("Start to search all available camera devices, please wait... ") |
| 69 | + cam_list = get_cam_lst() |
| 70 | + err_msg = "cannot find any video device!" |
| 71 | + else: |
| 72 | + cam_list = get_cam_lst(video_list) |
| 73 | + err_msg = "cannot find available video device in list: {0}!".format(video_list) +\ |
| 74 | + "\nPlease check the video devices in /dev/v4l/by-path/ folder!" |
| 75 | + |
| 76 | + if len(cam_list) < 1: |
| 77 | + print("ERROR: " + err_msg) |
| 78 | + return |
| 79 | + |
| 80 | + print("Available video device list is {}".format(cam_list)) |
| 81 | + caps = init_caps(cam_list) |
| 82 | + show_cam_img(caps, cam_list) |
| 83 | + deinit_caps(caps) |
| 84 | + |
| 85 | +if __name__ == "__main__": |
| 86 | + # User can specify the video list here. |
| 87 | + #show_cameras([2, 6, 10, 14]) |
| 88 | + |
| 89 | + # Or search all available video devices automatically. |
| 90 | + show_cameras() |
0 commit comments