import numpy as np
import cv2
from time import sleep
import queue
class MHI:
def __init__(self,cap,tau,delta,xi,t):
self.tau=tau
self.delta=delta
self.xi=xi
self.t=t
self.cap=cap
self.data = queue.Queue()
ret,frame=cap.read()
if ret:
for i in range(t):
self.data.put(frame)
self.H = np.zeros(frame.shape)
def getimag(self):
ret,frame=cap.read()
if not ret:
return ret,frame
self.data.put(frame)
old_frame=self.data.get()
a=cv2.addWeighted(old_frame.astype(float),1, frame.astype(float), -1, 0)
D= np.fabs(a)
Psi= D >=self.xi
c=self.H-self.delta
H=np.maximum(0,c)
H[Psi]=self.tau
self.H=H
return ret, H.astype("uint8")
### cv2.videocapture: 参数为0,表示打开笔记本内置摄像头 参数为路径则打开视频
cap = cv2.VideoCapture("E:/car_running/ori_video/car_running1.mp4")
#cap = cv2.VideoCapture(0)
#a=MHI(cap,tau=200,xi=20,delta=10,t=1)
## 参数可调: tau:持续时间(用帧数决定运动范围)xi:衰退函数 delta:帧间距离
a=MHI(cap,tau=100,xi=20,delta=10,t=1)
#############################
# video_dir = "E:/car_running/ori_video/HMI1.mp4"
# size = (520,738)
# fps = 30
# fourcc = cv2.VideoWriter_fourcc(*"mp4v")
# videoWrite = cv2.VideoWriter(video_dir,fourcc,fps,size)
#############################
path = 'E:/car_running/HMI/1/'+'/{}' #抽帧图片的保存路径
n = 0
i = 1
timeF = 20
while cap.isOpened():
n = n+1
_,frame=a.getimag() # 接入了电脑摄像头画面
cv2.imshow("out_win", frame)
if (n%timeF == 0):
print(i)
filename = str(i)+'.jpg'
cv2.imwrite(path.format(filename),frame)
i=i+1
sleep(0.04)
if cv2.waitKey(1) == ord('q'):
break
frame2video(frame,video_dir,fps)
cap.release()
# videoWrite.release()
cv2.destroyAllWindows()
python-opencv读入视频并形成运动历史图(HMI)并抽帧保存
于 2022-01-10 20:23:20 首次发布