首页 > 解决方案 > 相同图像的两个副本上的图像减法不给出零矩阵?

问题描述

我正在编写一个代码来从视频中提取帧并每两个连续帧减去一次,这样我就可以知道图像中运动实际开始的位置。据我所知,在减去这些帧(如果它们相等)之后,我应该得到一个全零矩阵。为了测试这一点,我在 adobe Premiere Pro 上制作了一个视频,其中静态图像延长了 5 秒。从视频中提取起始帧后,我将它们发送到此函数,但它显示矩阵中有多个非零元素,这意味着图像不同。我很困惑,请帮助。PS:是否会有任何元数据存储在图像本身中,是因为这个错误吗?

这是我用来从图像中提取帧的代码:-

enter code here
import cv2
import math
videoname = "mod_vdo.mp4"
imagesloc = "C:\\Users\\ANJANIPRASAD\\PycharmProjects\\Sin\\frames1"
vdoobject = cv2.VideoCapture(videoname)
fr = vdoobject.get(5) #gets the frame rate of the video
print(fr)
success = 1
frameCount = vdoobject.get(cv2.CAP_PROP_FRAME_COUNT)
frc=math.floor(fr)
duration=math.floor(frameCount/fr)
print(duration)
x=1
while x<=duration and success:
# vidObj object calls read
# function extract frames
frameId = vdoobject.get(1)
success, image = vdoobject.read()

if (frameId % frc == 0): #if fr is 24fps, 24rth, 48th, 72 etc will be extracted one by one
    filename = imagesloc + "/image_" + str(int(x)) + ".jpg";x=x+1
    cv2.imwrite(filename, image)
vdoobject.release()
print("Done!")

这每秒提取一帧(准确地说是每秒的最后一帧)

这是我用来比较帧的代码:

import cv2
import os
import numpy as np
from keras.preprocessing import image

dir="C:\\Users\\ANJANIPRASAD\\PycharmProjects\\Sin\\frames1"
j=1
for filename in os.listdir(dir):
 if filename.endswith('.jpg'):
    im1 = cv2.imread(dir + '/image_'+str(j)+'.jpg')
    im2= cv2.imread(dir+'/image_'+str(j+1)+'.jpg')
    if im1.shape==im2.shape:
        diff=cv2.subtract(im1,im2)
        b,g,r=cv2.split(diff)
        if cv2.countNonZero(b)==0 and cv2.countNonZero(g)==0 and 
         cv2.countNonZero(r)==0:
            j=j+1
            continue
        else:
            print('Start from the frame '+str(j)+' as the consecutive frames 
      are different')
            break

我在这些图像之间得到了 287829 个不同的像素。以下是图片: https ://drive.google.com/open?id=1t14fpcQImVldIrxW0C1Zvz3MWMliDWUr

标签: pythonopencvimage-processingvideo-processing

解决方案


当我跳过初始帧的检查并从第 3 帧开始检查时,它起作用了。我将 j 初始化为 3。也许一些额外的元数据存储在前 2 个提取的帧中,因为即使它们占用的 MB 量也不同。


推荐阅读