如何将前一帧保存在数组中并将其与python中的当前帧进行比较

问题描述

我想删除重复的对象,所以当相机打开它捕获第一帧并保存在磁盘上,然后直到下一个对象出现在场景中它保存下一个对象帧(不连续保存同一帧).

我编写了一个代码来比较两个连续的网络摄像头帧,我想将一帧存储在一个数组中(最大限制为 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()

解决方法

不难。

实际上,您可以将图像作为 NumPy 数组获取。 形状为 (720,1280,3).

enter image description here

要保存它,试试这个

      ...
      ret,frame1 = cap.read(0)  # first image
      
      print(frame1.shape)
      rgb_frame1 = frame1[...,::-1]
      im = Image.fromarray(rgb_frame1)
      im.save("your_file.jpeg")
      
      time.sleep(1/50)          # slight delay
      ...

注意:您需要更改频道顺序,否则您将获得蓝色图像。因为原来的频道是BRG格式的。

enter image description here

然后就可以存储框架了:

enter image description here