Skip to main content

Rudimentary idea to discover where a puzzle piece would fit (OpenCV)

I was doing a puzzle and I had this idea to have fun with OpenCV. There are many other things that should be done before having a proper solution, but it was good enough at that time.

Piece Full Picture

Split the puzzle
import numpy
from PIL import Image

square = 600
image ='santa_full.png')
width, height = image.size

for y in range(0, height, square):
for x in range(0, width, square):
image_cropped = image.crop((x, y, x+square, y+square)).convert('RGB')
pixels = image_cropped.getdata()"images/{}-{}.png".format(x/square, y/square), "PNG")
Discover where a piece would fit
import cv2

method = cv2.TM_SQDIFF_NORMED

# Read the images from the file
small_image = cv2.imread('images_puzzle_find_piece.png')
large_image = cv2.imread('images_puzzle_find_full.jpg')

result = cv2.matchTemplate(small_image, large_image, method)

# We want the minimum squared difference
mn,_,mnLoc,_ = cv2.minMaxLoc(result)

# Draw the rectangle: Extract the coordinates of our best match
MPx,MPy = mnLoc

# Step 2: Get the size of the template. This is the same size as the match.
trows,tcols = small_image.shape[:2]

# Step 3: Draw the rectangle on large_image
cv2.rectangle(large_image, (MPx,MPy),(MPx+tcols,MPy+trows),(0,0,255),2)

cv2.imwrite('result.jpg', large_image)