python - 使用 python 查找视频中的图像

标签 python opencv computer-vision object-detection

我想知道我是否以正确的方式处理这个问题,或者是否有一种更有效的方法。

我正在尝试寻找视频内的图像,就像在视频的每一帧上,该图像可能包含在其中的某个位置(它不是全尺寸的帧,只是一个小帧)。

目前正在将视频拉入图片中,如下所示:

import cv2
vidcap = cv2.VideoCapture('My_Video.mp4')
success,image = vidcap.read()
count = 0
success = True
while success:
  success,image = vidcap.read()
  print ('Read a new frame: ', success)
  cv2.imwrite("frame%d.jpg" % count, image)     # save frame as JPEG file
  count += 1

然后像这样循环遍历它们:

import cv2
import numpy as np
from matplotlib import pyplot as plt

img_rgb = cv2.imread('frame1.png')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('small_icon_I_am_looking_for.png',0)
w, h = template.shape[::-1]

res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( res >= threshold)
for pt in zip(*loc[::-1]):
    cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)

cv2.imwrite('res.png',img_rgb)

有没有办法可以跳过图片的保存?我在数千小时的视频中执行此操作,并保存和删除我认为会占用大量可能不需要的时间的每一帧。有什么想法如何可以搜索这个而不需要每次保存图片?这是我的意思的一个例子,假设有一个正在播放 super 马里奥的视频,它会寻找这个硬币:

Coin

并这样检测它:

Coin detected

这目前有效,但只是在寻找更好的方法。

最佳答案

如果我没有误解你的意思,下面的内容应该有效。总的来说,您的代码编写得很好,只需进行最少的更改即可完成您所要求的操作。由于 while 循环的结构,您丢弃第一帧也存在问题。避免这种情况的一个好方法是循环半/while True 构造:

import cv2
import numpy as np

def process_image(img_rgb, template, count):
    img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
    
    w, h = template.shape[::-1]

    res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
    threshold = 0.8
    loc = np.where( res >= threshold)
    for pt in zip(*loc[::-1]):
        cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)

    # This will write different res.png for each frame. Change this as you require
    cv2.imwrite('res{0}.png'.format(count),img_rgb)   


def main():
    vidcap = cv2.VideoCapture('My_Video.mp4')
    template = cv2.imread('small_icon_I_am_looking_for.png',0)  # open template only once
    count = 0
    while True:
      success,image = vidcap.read()
      if not success: break         # loop and a half construct is useful
      print ('Read a new frame: ', success)
      process_image(image, template, count)
      count += 1

关于python - 使用 python 查找视频中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41336746/

相关文章:

python - 使用 Django Rest Framework 和 IOS 应用程序时要使用哪种身份验证?

python - 沿y轴逐行旋转(对齐)图像

c++ - 在 C++ OpenCV 中使用相同的变量作为输入和输出是否安全?

computer-vision - 为什么ssd和yolo没有roi池化层?

python - 类型错误:使用 %s 时格式字符串的参数不足

python - 从 python 评估 "Shell command line with shell variables"或将 python 字符串评估为 shell 命令行

python - 为什么 pythonics 更喜欢 pip 而不是他们操作系统的包管理器?

c++ - OpenCV cv::Mat 到 std::ifstream 进行 base64 编码

opencv - 特征检测-大图中的小元素

python - 使用 Python OpenCV cv2.VideoCapture() 直接读取灰度视频帧