File size: 2,157 Bytes
690ada3
 
 
42b03f9
690ada3
 
3a834c5
 
 
 
 
dc979d2
 
3a834c5
20347ea
 
 
48e5876
20347ea
48e5876
 
20347ea
 
690ada3
48e5876
690ada3
9f64b92
 
690ada3
9f64b92
 
 
 
 
 
 
 
690ada3
27b7cb5
 
 
 
9f64b92
 
27b7cb5
 
690ada3
 
 
 
 
9f64b92
690ada3
 
 
9f64b92
690ada3
 
 
535b225
 
 
 
 
 
 
 
9f64b92
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import numpy as np
from skimage.metrics import structural_similarity as ssim
import gradio as gr
import cv2

# Function to calculate SSIM between two images
def calculate_similarity(img1, img2):
    if len(img1.shape) == 2:
        img1 = cv2.cvtColor(img1, cv2.COLOR_GRAY2RGB)
    if len(img2.shape) == 2:
        img2 = cv2.cvtColor(img2, cv2.COLOR_GRAY2RGB)
    return ssim(img1, img2, win_size=3)


# Function to compute similarity scores for all images
def compute_similarity(target_image, image_list):
    scores = []
    target_image_resized = cv2.resize(target_image, (target_image.shape[1], target_image.shape[0]))
    for image in image_list:
        image_resized = cv2.resize(image, (target_image.shape[1], target_image.shape[0]))
        similarity_score = calculate_similarity(target_image_resized, image_resized)
        scores.append(similarity_score)
    return scores


# Function to handle the Gradio interface
# Function to handle the Gradio interface
def image_similarity(target_image, image_list):
    target_image = target_image.astype(np.uint8)
    image_list = [image.astype(np.uint8) for image in image_list]
    scores = compute_similarity(target_image, image_list)
    results = []
    for image, score in zip(image_list, scores):
        formatted_image = format_image(image)
        result = f"Image: {formatted_image}\nScore: {score:.4f}\n"
        results.append(result)
    return "".join(results)

# Function to format the image representation as a string
def format_image(image):
    formatted_image = ""
    for row in image:
        formatted_row = ", ".join([f"[{', '.join(map(str, pixel))}]" for pixel in row])
        formatted_image += f"[{formatted_row}],\n"
    return formatted_image[:-2]

# Prepare Gradio interface
iface = gr.Interface(
    fn=image_similarity,
    inputs=[
        gr.inputs.Image(type="numpy", label="Target Image"),
        gr.inputs.Image(type="numpy", label="Image List", multiple=True)
    ],
    outputs="text",
    title="Image Similarity Calculator",
    description="Upload a target image and a list of images. Get similarity scores."
)

# Launch the interface
iface.launch()