Finding a Small Image Within a Larger Image Using Python and OpenCV

In this post, we’ll explore an interesting application of image processing using the Python programming language and the OpenCV library. The topic of this post is finding a small image within a larger image. This application can be used for pattern recognition, image matching, or even face detection.

First, make sure that OpenCV is installed in your Python environment. If you haven’t installed it yet, you can do so using the following commands:

pip install opencv-python
pip install opencv-python-headless

 

Now that OpenCV is installed, let’s delve into the Python code for finding an image within an image. The following code accomplishes this task:

import cv2

def find_image_in_larger_image(small_image_path, large_image_path):
# Read images
small_image = cv2.imread(small_image_path, cv2.IMREAD_GRAYSCALE)
large_image = cv2.imread(large_image_path, cv2.IMREAD_GRAYSCALE)

# Check if images are loaded successfully
if small_image is None or large_image is None:
print(“Error: Unable to load images.”)
return None

# Get dimensions of both images
small_height, small_width = small_image.shape
large_height, large_width = large_image.shape

# Find the template (small image) within the larger image
result = cv2.matchTemplate(large_image, small_image, cv2.TM_CCOEFF_NORMED)

# Define a threshold to consider a match
threshold = 0.8

# Find locations where the correlation coefficient is greater than the threshold
locations = cv2.findNonZero((result >= threshold).astype(int))

# If no match is found
if locations is None:
print(“No match found.”)
return None

# Draw rectangles around the matching areas
for loc in locations:
top_left = loc[0]
bottom_right = (top_left[0] + small_width, top_left[1] + small_height)
cv2.rectangle(large_image, top_left, bottom_right, (0, 255, 0), 2)

# Display the result (optional)
cv2.imshow(“Result”, large_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

return locations

# Example usage
small_image_path = “small_image.jpg”
large_image_path = “large_image.jpg”

find_image_in_larger_image(small_image_path, large_image_path)

This code finds occurrences of the small image within the larger image and draws rectangles around the matching areas.

By running this code and replacing "small_image.jpg" and "large_image.jpg" with the paths to your actual images, you can experience its functionality.