DecorSearch / similarity_module.py
rishitchugh's picture
initial
43cea81
import cv2
import os
import numpy as np
from PIL import Image
import shutil
def resize_image(image_path, target_width=800, target_height=600):
# Get the directory path and filename
directory, filename = os.path.split(image_path)
# Create the output directory if it doesn't exist
output_directory = os.path.join(directory, 'outputs')
os.makedirs(output_directory, exist_ok=True)
try:
# Open the image
with Image.open(image_path) as img:
# Resize the image
resized_img = img.resize((target_width, target_height))
# Save the resized image to the output folder with the same name and extension
output_path = os.path.join(output_directory, filename)
resized_img.save(output_path)
print("Image saved successfully:", output_path)
return output_path
except Exception as e:
print("Error occurred while resizing image:", e)
return None
def get_top_similar_images(input_image_path, images_folder_path, top_n=5):
try:
# Resize input image
print("Resizing input image...")
resized_input_image_path = resize_image(input_image_path)
print("Input image resized:", resized_input_image_path)
# Read resized input image
resized_input_image = cv2.imread(resized_input_image_path)
print("Input image read successfully")
# Convert input image to HSV
hsv_input = cv2.cvtColor(resized_input_image, cv2.COLOR_BGR2HSV)
hist_input = cv2.calcHist([hsv_input], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])
# Calculate Bhattacharyya distance for all images in the folder
distances = {}
print(images_folder_path)
for filename in os.listdir(images_folder_path):
image_path = os.path.join(images_folder_path, filename)
print(image_path)
if os.path.isfile(image_path):
# Read image
image = cv2.imread(image_path)
print("Image read successfully:", image_path)
# Convert image to HSV (no need to resize again)
hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
hist_image = cv2.calcHist([hsv_image], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])
# Calculate Bhattacharyya distance
distance = cv2.compareHist(hist_input, hist_image, cv2.HISTCMP_BHATTACHARYYA)
distances[filename] = distance
# Sort distances by increasing order
sorted_distances = sorted(distances.items(), key=lambda x: x[1])
print("Distances calculated successfully")
# Return top similar images
return sorted_distances[:top_n]
except Exception as e:
print("Error occurred during image comparison:", e)
return []
# Example usage
def move_images_to_folder(images, destination_folder):
try:
# Empty the destination folder
shutil.rmtree(destination_folder, ignore_errors=True)
os.makedirs(destination_folder, exist_ok=True)
# Move images to the destination folder
for filename in images:
shutil.copy(os.path.join('./resized_img', filename), destination_folder)
except Exception as e:
print("Error occurred while moving images to folder:", e)