Login
main >   template_matching >  


Template matching

https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_template_matching/py_template_matching.html#template-matching

"""https://www.geeksforgeeks.org/python-document-field-detection-using-template-matching/
"""

import cv2
import imutils
import numpy as np
import os
import sys


#Filenames starting with, will detect if
field_threshold = {
    'existing_member.png' : 0.7,
    'title.png' : 0.6,
}

# Function to Generate bounding 
# boxes around detected fields 
def getBoxed(img, img_gray, template, field_name):

    w, h = template.shape[::-1]

    # Apply template matching 
    res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
    
    
    hits = np.where(res >= field_threshold[field_name])

    # Draw a rectangle around the matched region.
    for pt in zip(*hits[::-1]):
        cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 255, 255), 2)
        y = pt[1] - 10 if pt[1] - 10 > 10 else pt[1] + h + 20

        cv2.putText(img, field_name, (pt[0], y), cv2.FONT_HERSHEY_SIMPLEX, 1.8, (0, 0, 255), 1)

        return(img, (pt[0] + w, pt[1] + h))


if __name__ == '__main__': 

    if len(sys.argv) < 3:
        print("Please enter a main filename and templates")
        valid_templates = ", ".join(field_threshold.keys())
        print(f"Current template files are: {valid_templates}")
        print("e.g. python find_section.py main.png template.png template2.png\n")
        sys.exit()

    files_exist = True
    for i, arg in enumerate(sys.argv):
        if not os.path.isfile(arg):
            print (f"File does not exist: {arg}")
            files_exist = False
    
    if not files_exist:
        print()
        sys.exit()

    main_image_filename = sys.argv[1]

    template_filenames = []
    for i, arg in enumerate(sys.argv[2:]):
        template_filenames.append(arg)

    # Read the original document image 
    img = cv2.imread(main_image_filename)
    img_gray = cv2.imread(main_image_filename, 0)
    
    # Field templates 
    for template_filename in template_filenames:
        template = cv2.imread(template_filename, 0)
        
        img, position = getBoxed(img.copy(), img_gray.copy(), template, template_filename)
        print(f"{template_filename}: {position}")
    
    cv2.imwrite("found.png",img)




hidden1

hidden2