Image Matching using NCC (normalized cross-correlation)

133 views Asked by At

enter image description here I have tried to implement NCC on two images but my code works only on small images when I try to input big images it's saying doing processing(Matching) without any output. can anyone tell me where is the problem please.

enter image description here

import numpy as np
import cv2
from matplotlib import pyplot as plt

# Normalized Cross Correlation
def ncc(roi, template):
    mean_roi = np.mean(roi)
    mean_template = np.mean(template)
    numerator = np.sum((roi - mean_roi) * (template - mean_template))
    denominator = np.sqrt(np.sum((roi - mean_roi) ** 2)) * np.sqrt(np.sum((template - mean_template) ** 2))
    return numerator / denominator

# Template Matching using NCC
def template_matching_ncc(image, template):   
    h, w = template.shape
    H, W = image.shape
    print("Template Matching using NCC")

    max_ncc = -1
    max_position = (0, 0)


    for y in range(H - h):
        for x in range(W - w):
            roi = image[y:y+h, x:x+w]
            current_ncc = ncc(roi, template)
            print("Matching")
            if current_ncc > max_ncc:
                max_ncc = current_ncc
                max_position = (x, y)
                print("max_position Matching")

    return max_position

# Read the images
print("Loading first image")
image = cv2.imread('./0711_study_area1.jpg', 0)  # Replace with your image path
print("Loading Second image")
template = cv2.imread('./0711_study_areaa.jpg', 0)  # Replace with your template path

print("Apply template matching")
# Apply template matching
top_left = template_matching_ncc(image, template)
bottom_right = (top_left[0] + template.shape[1], top_left[1] + template.shape[0])

# Draw a rectangle on the matched region
print("Draw a rectangle on the matched region")
cv2.rectangle(image, top_left, bottom_right, 255, 2)

# Show the result
plt.imshow(image, cmap='gray')
plt.title("Template Matching using NCC")
plt.show()
0

There are 0 answers