video_v4l2.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/usr/bin/env python
  2. '''
  3. VideoCapture sample showcasing some features of the Video4Linux2 backend
  4. Sample shows how VideoCapture class can be used to control parameters
  5. of a webcam such as focus or framerate.
  6. Also the sample provides an example how to access raw images delivered
  7. by the hardware to get a grayscale image in a very efficient fashion.
  8. Keys:
  9. ESC - exit
  10. g - toggle optimized grayscale conversion
  11. '''
  12. # Python 2/3 compatibility
  13. from __future__ import print_function
  14. import numpy as np
  15. import cv2 as cv
  16. def main():
  17. def decode_fourcc(v):
  18. v = int(v)
  19. return "".join([chr((v >> 8 * i) & 0xFF) for i in range(4)])
  20. font = cv.FONT_HERSHEY_SIMPLEX
  21. color = (0, 255, 0)
  22. cap = cv.VideoCapture(0)
  23. cap.set(cv.CAP_PROP_AUTOFOCUS, 0) # Known bug: https://github.com/opencv/opencv/pull/5474
  24. cv.namedWindow("Video")
  25. convert_rgb = True
  26. fps = int(cap.get(cv.CAP_PROP_FPS))
  27. focus = int(min(cap.get(cv.CAP_PROP_FOCUS) * 100, 2**31-1)) # ceil focus to C_LONG as Python3 int can go to +inf
  28. cv.createTrackbar("FPS", "Video", fps, 30, lambda v: cap.set(cv.CAP_PROP_FPS, v))
  29. cv.createTrackbar("Focus", "Video", focus, 100, lambda v: cap.set(cv.CAP_PROP_FOCUS, v / 100))
  30. while True:
  31. _status, img = cap.read()
  32. fourcc = decode_fourcc(cap.get(cv.CAP_PROP_FOURCC))
  33. fps = cap.get(cv.CAP_PROP_FPS)
  34. if not bool(cap.get(cv.CAP_PROP_CONVERT_RGB)):
  35. if fourcc == "MJPG":
  36. img = cv.imdecode(img, cv.IMREAD_GRAYSCALE)
  37. elif fourcc == "YUYV":
  38. img = cv.cvtColor(img, cv.COLOR_YUV2GRAY_YUYV)
  39. else:
  40. print("unsupported format")
  41. break
  42. cv.putText(img, "Mode: {}".format(fourcc), (15, 40), font, 1.0, color)
  43. cv.putText(img, "FPS: {}".format(fps), (15, 80), font, 1.0, color)
  44. cv.imshow("Video", img)
  45. k = cv.waitKey(1)
  46. if k == 27:
  47. break
  48. elif k == ord('g'):
  49. convert_rgb = not convert_rgb
  50. cap.set(cv.CAP_PROP_CONVERT_RGB, 1 if convert_rgb else 0)
  51. print('Done')
  52. if __name__ == '__main__':
  53. print(__doc__)
  54. main()
  55. cv.destroyAllWindows()