当前位置:   article > 正文

python调用openCV方法

python调用opencv

环境:

安装pip install opencv-python

如果报错

控制面板路径,cd到C:\Users\"username"\AppData\Local\Programs\Python\Python310\Scripts

再执行pip install opencv-python

python调用摄像头拍照并保存

  1. import cv2
  2. import os
  3. #引入库
  4. print("=============================================")
  5. print("= 热键(请在摄像头的窗口使用): =")
  6. print("= z: 更改存储目录 =")
  7. print("= x: 拍摄图片 =")
  8. print("= q: 退出 =")
  9. print("=============================================")
  10. #提醒用户操作字典
  11. class_name = input("请输入存储目录(python安装目录下才行,如:d:\python\py_image):")
  12. if not os.path.exists(class_name):
  13. os.mkdir(class_name)
  14. #存储
  15. index = 1
  16. cap = cv2.VideoCapture(0 + cv2.CAP_DSHOW)
  17. width = 640
  18. height = 480
  19. w = 360
  20. cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
  21. cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
  22. crop_w_start = (width-w)//2
  23. crop_h_start = (height-w)//2
  24. print(width, height)
  25. #设置特定值
  26. while True:
  27. ret, frame = cap.read()
  28. frame = frame[crop_h_start:crop_h_start+w, crop_w_start:crop_w_start+w]
  29. #没理解?
  30. frame = cv2.flip(frame,1,dst=None)
  31. #镜像显示
  32. cv2.imshow("capture", frame)
  33. #显示
  34. input = cv2.waitKey(1) & 0xFF
  35. if input == ord('z'):
  36. class_name = input("请输入存储目录:")
  37. while os.path.exists(class_name):
  38. class_name = input("目录已存在!请输入存储目录:")
  39. os.mkdir(class_name)
  40. #存储
  41. elif input == ord('x'):
  42. cv2.imwrite("%s/%d.jpeg" % (class_name, index),
  43. cv2.resize(frame, (224, 224), interpolation=cv2.INTER_AREA))
  44. print("%s: %d 张图片" % (class_name, index))
  45. index += 1
  46. #?
  47. if input == ord('q'):
  48. break
  49. #退出
  50. cap.release()
  51. cv2.destroyAllWindows()
  52. #关闭窗口

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号