Код: Выделить всё
import cv2
import numpy as np
# Load images
img1 = cv2.imread('C:/Users/Autobobcat/Desktop/Candy- crush.23.jpg', cv2.IMREAD_COLOR) # Query image
img2 = cv2.imread('C:/Users/Autobobcat/Desktop/blueVertical.png', cv2.IMREAD_COLOR) # Training image
# Convert images to grayscale
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# Create SIFT detector
sift = cv2.SIFT_create()
# Find the keypoints and descriptors with SIFT
kp1, des1 = sift.detectAndCompute(gray1, None)
kp2, des2 = sift.detectAndCompute(gray2, None)
# Create BFMatcher object with default parameters
bf = cv2.BFMatcher()
# Match descriptors using KNN
matches = bf.knnMatch(des1, des2, k=2)
# Apply ratio test with a more lenient threshold
good_matches = []
for m, n in matches:
if m.distance < 0.3 * n.distance: # Adjusted ratio test
good_matches.append(m)
# Sort matches by distance
good_matches = sorted(good_matches, key=lambda x: x.distance)
# Draw matches
img_matches = cv2.drawMatches(img1, kp1, img2, kp2,
good_matches[:50], None,
flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)
# Define target screen size
target_width = 1280
target_height = 720
# Calculate the aspect ratio of the image
(h, w) = img_matches.shape[:2]
aspect_ratio = w / h
# Determine the new size keeping the aspect ratio
if w > target_width or h > target_height:
if aspect_ratio > 1: # Image is wider than tall
new_width = target_width
new_height = int(target_width / aspect_ratio)
else: # Image is taller than wide
new_height = target_height
new_width = int(target_height * aspect_ratio)
else:
new_width, new_height = w, h
dim = (new_width, new_height)
# Resize image
resized_img_matches = cv2.resize(img_matches, dim,
interpolation=cv2.INTER_AREA)
# Display the result
cv2.imshow('Feature Matching', resized_img_matches)
cv2.waitKey(0)
cv2.destroyAllWindows()

< img alt="изображение шаблона" src="https://i.sstatic.net/oTFjJYhA.png" />
[img]https://i.sstatic. net/CU6V61or.png[/img]
Подробнее здесь: https://stackoverflow.com/questions/788 ... -the-image