You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.5 KiB

import os
import cv2
import threading
outputFrame = None
lock = threading.Lock()
class CvCamera():
def __init__(self):
# 获取当前相机
self.cap = None
self.workFlag =False
self.record_id =None
self.video_path = 'D:/Project/UI/videoFold'
self.fourcc = cv2.VideoWriter_fourcc(*'XVID')
if not os.path.exists(self.video_path) or not os.path.isdir(self.video_path):
os.makedirs(self.video_path)
#打开相机
def start(self,record_id=None):
try:
if self.workFlag == False:
self.record_id =record_id
self.cap = cv2.VideoCapture(0)
self.workFlag = True
# 单独线程供相机使用
t = threading.Thread(target=self.videoWork)
t.start()
except Exception as e:
print(e)
# 释放资源
def release(self):
global outputFrame
try:
self.workFlag = False
self.record_id = None
if (self.cap):
outputFrame=None
self.cap.release()
except:
pass
# 相机图像分析
def videoWork(self):
global outputFrame, lock
self.cap.set(cv2.CAP_PROP_FPS, 30)
out = cv2.VideoWriter(self.video_path + '/' + self.record_id + '.mp4', self.fourcc, 20.0, (640, 480))
while (self.workFlag):
try:
ret, frame = self.cap.read()
# cv2.imshow('image',frame)
# cv2.waitKey(0)
with lock:
outputFrame = frame.copy()
out.write(frame)
except Exception as e:
print(e)
# 输出图像
def generate(self):
# 抓取对输出帧和锁定变量的全局引用
global outputFrame, lock
# 循环访问输出流中的帧
while True:
# 等到锁被获取
with lock:
# 检查输出帧是否可用,否则跳过
# 循环的迭代
if outputFrame is None:
continue
# 以 JPEG 格式对帧进行编码
(flag, encodedImage) = cv2.imencode(".jpg", outputFrame)
# 确保帧已成功编码
if not flag:
continue
# 以字节格式生成输出帧
yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + bytearray(encodedImage) + b'\r\n')