无法识别视频中的对象

时间:2019-01-20 15:26:45

标签: python opencv cv2

我正在做一个学校项目。

我被赋予了在用相机看到物体时识别物体的任务。

Video

Image

我选择尝试template matching

from matplotlib import pyplot as plt
import cv2

template = cv2.imread('./frog.jpg') # read image as template
cap = cv2.VideoCapture('./frog.mov') # simulate camera input

height = template.shape[0]
width = template.shape[1]

while True:
    ret, frame = cap.read() # read the current frame

    if ret is False:
        break
    res = cv2.matchTemplate(frame, template, cv2.TM_CCORR_NORMED)

    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

    top_left = max_loc
    bottom_right = (top_left[0] + width, top_left[1] + height)

    cv2.rectangle(frame,top_left, bottom_right, 255, 2)

    match_found = False

    for i in res:
        if i.any() > 0.9999:
            print ('match found')
            match_found = True
            break 

    if match_found:
        plt.subplot(121),plt.imshow(res,cmap = 'gray')
        plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
        plt.subplot(122),plt.imshow(frame,cmap = 'gray')
        plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
        plt.suptitle('TM_CCORR_NORMED')
        plt.show()

问题是,几乎所有东西都匹配。 我该如何使用它?

1 个答案:

答案 0 :(得分:1)

如果您将使用frogbear图像,则将获得100%匹配的对象。以下脚本在视频上检测到这些图像并显示检测到的对象的名称:

from matplotlib import pyplot as plt
import cv2

images = {'Frog': cv2.imread('frog.jpg'), 'Bear': cv2.imread('bear.jpg')}
cap = cv2.VideoCapture('frog.mov')  # simulate camera input

while cap.isOpened():
    ret, frame = cap.read()  # read the current frame
    if ret:
        for name, image in images.items():
            match = cv2.matchTemplate(frame, image, cv2.TM_CCOEFF_NORMED)
            _, quality, _, max_loc = cv2.minMaxLoc(match)
            if quality > 0.99:

                top_left = max_loc
                bottom_right = (top_left[0] + image.shape[1], top_left[1] + image.shape[0])
                cv2.rectangle(frame, top_left, bottom_right, 255, 2)
                plt.subplot(121), plt.imshow(match, cmap='gray')
                plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
                plt.subplot(122), plt.imshow(frame, cmap='gray')
                plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
                plt.suptitle(name)
                plt.show()
    else:
        break

那我到底有什么?

enter image description here enter image description here