https://blog.csdn.net/qq_42403190/article/details/90453305
创建文件
camera.py
简单读取
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import numpy as np import cv2 cap = cv2.VideoCapture(0) # 从摄像头中取得视频 # 获取视频播放界面长宽 width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) + 0.5) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) + 0.5) # 定义编码器 创建 VideoWriter 对象 fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Be sure to use the lower case out = cv2.VideoWriter('output.mp4', fourcc, 20.0, (width, height)) while(cap.isOpened()): #读取帧摄像头 ret, frame = cap.read() if ret == True: #输出当前帧 out.write(frame) cv2.imshow('My Camera',frame) #键盘按 Q 退出 if (cv2.waitKey(1) & 0xFF) == ord('q'): break else: break # 释放资源 out.release() cap.release() cv2.destroyAllWindows()
处理融合
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import cv2 import numpy as np name = 0 cap = cv2.VideoCapture(0) cap.set(3,640) cap.set(4,480) ret, frame = cap.read() rows, cols, channels = frame.shape print(cols, rows, channels) # 图像预处理 def img_p(img): # 灰度化 gray_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # 平滑滤波 blur = cv2.blur(gray_img, (3,3)) # 二值化 ret1, th1 = cv2.threshold(blur, 190, 255, cv2.THRESH_BINARY) # 透视变换 b = 50 pts1 = np.float32([[b, 0], [cols-b, 0], [0, rows], [cols, rows]]) pts2 = np.float32([[0, 0], [cols, 0], [0, rows], [cols, rows]]) M = cv2.getPerspectiveTransform(pts1, pts2) dst = cv2.warpPerspective(blur, M, (cols, rows)) return dst while(1): ret,frame = cap.read() dst = img_p(frame) cv2.imshow('usb camera', dst) k = cv2.waitKey(50) if (k == ord('q')): break elif(k == ord('s')): #name = input('name:') name += 1 filename = r'./camera/' + str(name) + '.jpg' cv2.imwrite(filename, dst) print(filename) #break cap.release() cv2.destroyAllWindows()
运行文件
python3 camera.py
结果: