<jupyter_start><jupyter_text>Codigo adaptado de https://www.sicara.ai/blog/object-detection-template-matching<jupyter_code>import cv2
import numpy as np
import matplotlib.pyplot as plt

# Se define un umbral para definir que si se encontro
# el match
DEFAULT_TEMPLATE_MATCHING_THRESHOLD = 0.5

# Se crea una clase en la cual se definiran todas
# las propiedades de los templates
class Template:
    
    def __init__(self, image_path, label, color, matching_threshold=DEFAULT_TEMPLATE_MATCHING_THRESHOLD):
        
        #Args:
        #    image_path (str): path of the template image path
        #    label (str): the label corresponding to the template
        #    color (List[int]): the color associated with the label (to plot detections)
        #    matching_threshold (float): the minimum similarity score to consider an object is detected by template
        #        matching
        
        self.image_path = image_path
        self.label = label
        self.color = color
        self.template = cv2.imread(image_path, 0)
        self.template_height, self.template_width = self.template.shape[:2]
        self.matching_threshold = matching_threshold

# Se crean los dos templates a buscar en la imagen
templates = [
    Template(image_path="imgs/lunar_sticker.png", label="1", color=(0, 0, 255)),
    Template(image_path="imgs/kinetic_sticker.png", label="2", color=(0, 255, 0)),
]

# Se carga la imagen
image = cv2.imread("imgs/Photo2.jpg")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
print("Image shape: ", image.shape)

# Se realiza la comparacion entre templates y la imagen
detections = []
img_gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

for template in templates:
    print(template.template.shape)
    template_matching = cv2.matchTemplate( template.template, img_gray, cv2.TM_CCOEFF_NORMED )

    match_locations = np.where(template_matching >= template.matching_threshold)

    for (x, y) in zip(match_locations[1], match_locations[0]):
        match = {
            "TOP_LEFT_X": x,
            "TOP_LEFT_Y": y,
            "BOTTOM_RIGHT_X": x + template.template_width,
            "BOTTOM_RIGHT_Y": y + template.template_height,
            "MATCH_VALUE": template_matching[y, x],
            "LABEL": template.label,
            "COLOR": template.color
        }
        
        detections.append(match)

print("Detections: ", len(detections))
        
# Se guarda una imagen en donde se dibujaran los objetos detectados
image_with_detections = image.copy()

for detection in detections:
    cv2.rectangle(
        image_with_detections,
        (detection["TOP_LEFT_X"], detection["TOP_LEFT_Y"]),
        (detection["BOTTOM_RIGHT_X"], detection["BOTTOM_RIGHT_Y"]),
        detection["COLOR"],
        2,
    )
    cv2.putText(
        image_with_detections,
        f"{detection['LABEL']} - {detection['MATCH_VALUE']}",
        (detection["TOP_LEFT_X"] + 2, detection["TOP_LEFT_Y"] + 20),
        cv2.FONT_HERSHEY_SIMPLEX,
        0.5,
        detection["COLOR"],
        1,
        cv2.LINE_AA,
    )
    
# Mostrar ambas imagenes
plt.figure(num=None, figsize=(15, 15), dpi=80, facecolor='w', edgecolor='k')
plt.subplot(1,2,1),plt.imshow(image), plt.title('Imagen izquierda')
plt.axis('off') 
plt.subplot(1,2,2),plt.imshow(image_with_detections), plt.title('Imagen derecha')
plt.axis('off') 
plt.show()<jupyter_output>Image shape:  (1280, 720, 3)
(530, 530)
(343, 400)
Detections:  0
{'fraction_non_alphanumeric': 0.11503649635036496, 'fraction_numerical': 0.021605839416058394, 'mean_word_length': 3.293233082706767, 'pattern_counts': {'":': 7, '<': 4, '<?xml version=': 0, '>': 5, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '310549', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 1203, 'n_tokens_neox': 1124, 'n_words': 259, 'path': '.ipynb_checkpoints/Template_Matching-checkpoint.ipynb', 'repo_name': 'jmfajardod/OpenCV_RyCSV_1', 'size': '3425'}