1 |
import cv2
|
2 |
import numpy as np
|
3 |
import os
|
4 |
import shutil
|
5 |
|
6 |
def find_logo(target_image_path, logo_image_gray, search_area=(800, 400), threshold=0.8):
|
7 |
"""Search for the logo within the specified area of the target image, focusing on the top right corner and handling grayscale images."""
|
8 |
# Load the target image and convert to grayscale
|
9 |
target_image = cv2.imread(target_image_path)
|
10 |
target_image_gray = cv2.cvtColor(target_image, cv2.COLOR_BGR2GRAY)
|
11 |
|
12 |
height, width = target_image_gray.shape
|
13 |
|
14 |
# Calculate the starting point for the crop to focus on the top right corner
|
15 |
start_x = width - search_area[0] # Width of the image minus the search area width
|
16 |
start_y = 0 # Start at the top of the image
|
17 |
|
18 |
# Crop the search area from the top right corner of the target image
|
19 |
search_area_cropped = target_image_gray[start_y:start_y + search_area[1], start_x:start_x + search_area[0]]
|
20 |
|
21 |
# Template matching
|
22 |
result = cv2.matchTemplate(search_area_cropped, logo_image_gray, cv2.TM_CCOEFF_NORMED)
|
23 |
_, max_val, _, _ = cv2.minMaxLoc(result)
|
24 |
|
25 |
return max_val >= threshold
|
26 |
|
27 |
def process_images(folder_path, logo_path, similar_folder="similar", threshold=0.8):
|
28 |
"""Process all images in the folder to find the logo within the top right area, considering grayscale images."""
|
29 |
# Convert the reference (logo) image to grayscale once
|
30 |
logo_image = cv2.imread(logo_path)
|
31 |
logo_image_gray = cv2.cvtColor(logo_image, cv2.COLOR_BGR2GRAY)
|
32 |
|
33 |
# Ensure the 'similar' folder exists
|
34 |
similar_folder_path = os.path.join(folder_path, similar_folder)
|
35 |
if not os.path.exists(similar_folder_path):
|
36 |
os.makedirs(similar_folder_path)
|
37 |
|
38 |
# Iterate through all images in the folder
|
39 |
for filename in os.listdir(folder_path):
|
40 |
if filename.endswith(('.png', '.jpg', '.jpeg')):
|
41 |
current_path = os.path.join(folder_path, filename)
|
42 |
try:
|
43 |
if find_logo(current_path, logo_image_gray, threshold=threshold):
|
44 |
# If the logo is found, move the image to the 'similar' folder
|
45 |
shutil.move(current_path, os.path.join(similar_folder_path, filename))
|
46 |
print(f"Moved {filename} to {similar_folder_path}.")
|
47 |
except Exception as e:
|
48 |
print(f"Error processing {filename}: {e}")
|
49 |
|
50 |
# Example usage
|
51 |
folder_path = 'path/to/your/pictures' # Update this to your pictures folder path
|
52 |
logo_path = 'logo.jpg' # Ensure this is the path to your logo
|
53 |
process_images(folder_path, logo_path)
|