问题描述
我想删除重复的对象,所以当相机打开它捕获第一帧并保存在磁盘上,然后直到下一个对象出现在场景中它保存下一个对象帧(不连续保存同一帧).
我编写了一个代码来比较两个连续的网络摄像头帧,我想将一帧存储在一个数组中(最大限制为 3)以将其与当前帧进行比较。所以第一帧将保存在磁盘上并进行比较直到下一个对象出现(为此使用阈值)
如何将帧保存到数组并与当前帧进行比较?
from skimage.metrics import structural_similarity
import imutils
import sys
import datetime
import cv2
import time
import numpy as np
cap = cv2.VideoCapture(0)
while (True):
# Capture frame-by-frame
ret,frame1 = cap.read(0) # first image
time.sleep(1/50) # slight delay
ret,frame2 = cap.read(0) # second image
gray1 = cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY)
# compute the Structural Similarity Index (SSIM) between the two
# images,ensuring that the difference image is returned
(score,diff) = structural_similarity (gray1,gray2,full=True)
diff = (diff * 255).astype ("uint8")
print ("SSIM: {}".format (score))
# threshold the difference image,followed by finding contours to
# obtain the regions of the two input images that differ
thresh = cv2.threshold (diff,255,cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
if np.mean (thresh) < 0.4 :
print ("New object Detected")
date_string = datetime.datetime.Now ( ).strftime ("%Y-%m-%d-%H:%M:%s")
cv2.imwrite ('img/img-' + date_string + '.png',frame2[y:y+h+30,x:x+w+30])
# display the resulting frame
cv2.imshow ('frame1',frame1)
cv2.imshow('frame2',frame2)
cv2.imshow ("Diff",diff)
cv2.imshow ("Thresh",thresh)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything is done,release the capture
video_capture.release()
cv2.destroyAllWindows()