G
G
getnaked2017-06-05 13:16:02
Python
getnaked, 2017-06-05 13:16:02

How to find one image inside another using opencv?

There is such a code, it does a great job with large color images. I needed to find out if there is a gray arrow (2.png) on ​​another image (1.png) and there is not a single match. The arrow has been cropped from the original image. What could be the problem with the color "too gray" after processing?
da01c62839464ac1a3484d1b3a79622a.png

spoiler
import cv2
import numpy as np
import matplotlib.pyplot as plt
import sys
import requests
import os

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

res = cv2.matchTemplate(img_gray,template,cv2.TM_SQDIFF_NORMED)
threshold = 0.4
loc = np.where( res >= threshold)

f = set()

for pt in zip(*loc[::-1]):
    cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)

    sensitivity = 60
    f.add((round(pt[0]/sensitivity), round(pt[1]/sensitivity)))

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

found_count = len(f)

if found_count >0:
    print ("found")
    
else:
    print ("not found")

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Mirilaczvili, 2019-06-05
@2ord

Probably just need to swap 1.png and 2.png in the code.
templateis a larger image than the desired one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question