本篇文章给大家分享的是有关怎么在python中使用openCV调用摄像头拍摄和处理图片,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
详细代码如下:
import cv2
import os
print("=============================================")
print("= 热键(请在摄像头的窗口使用): =")
print("= z: 更改存储目录 =")
print("= x: 拍摄图片 =")
print("= q: 退出 =")
print("=============================================")
print()
class_name = input("请输入存储目录:")
while os.path.exists(class_name):
class_name = input("目录已存在!请输入存储目录:")
os.mkdir(class_name)
index = 1
cap = cv2.VideoCapture(0)
width = 640
height = 480
w = 360
cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
crop_w_start = (width-w)//2
crop_h_start = (height-w)//2
print(width, height)
while True:
# get a frame
ret, frame = cap.read()
# show a frame
frame = frame[crop_h_start:crop_h_start+w, crop_w_start:crop_w_start+w]
frame = cv2.flip(frame,1,dst=None)
cv2.imshow("capture", frame)
input = cv2.waitKey(1) & 0xFF
if input == ord('z'):
class_name = input("请输入存储目录:")
while os.path.exists(class_name):
class_name = input("目录已存在!请输入存储目录:")
os.mkdir(class_name)
elif input == ord('x'):
cv2.imwrite("%s/%d.jpeg" % (class_name, index),
cv2.resize(frame, (224, 224), interpolation=cv2.INTER_AREA))
print("%s: %d 张图片" % (class_name, index))
index += 1
if input == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
要点记录:
当前版本opencv-python(3.4.3.18)中摄像头有关属性为cv2.XXXX,其获取和设置函数分别如下:(以帧的宽和高为例)
# 获取
width = int(videoCapture.get(cv2.CV_CAP_PROP_FRAME_WIDTH)
height = int(videoCapture.get(cv2.CV_CAP_PROP_FRAME_HEIGHT)
# 设置
cv2.VideoCapture(0).set(cv2.CAP_PROP_FRAME_WIDTH, width)
cv2.VideoCapture(0).set(cv2.CAP_PROP_FRAME_HEIGHT, height)
以上就是怎么在python中使用openCV调用摄像头拍摄和处理图片,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。