How do I find an image contained within an image?

后端 未结 3 1649
灰色年华
灰色年华 2020-11-30 20:38

I\'m currently building what basically amounts to a cross between a search engine and a gallery for web comics that\'s focused on citing sources and giving authors credit.

3条回答
  •  天涯浪人
    2020-11-30 21:12

    As Moshe's answer only covers matching a template that is contained only once in the given picture. Here's how matching several at once:

    import cv2
    import numpy as np
    
    img_rgb = cv2.imread('mario.png')
    template = cv2.imread('mario_coin.png')
    w, h = template.shape[:-1]
    
    res = cv2.matchTemplate(img_rgb, template, cv2.TM_CCOEFF_NORMED)
    threshold = .8
    loc = np.where(res >= threshold)
    for pt in zip(*loc[::-1]):  # Switch collumns and rows
        cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
    
    cv2.imwrite('result.png', img_rgb)
    

    (Note: I changed and fixed a few 'mistakes' that were in the original code)

    Result:

    Source: https://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_imgproc/py_template_matching/py_template_matching.html

提交回复
热议问题