Ali Asgarov
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import numpy as np
|
3 |
+
import tensorflow as tf
|
4 |
+
from tensorflow.keras.applications import MobileNetV2
|
5 |
+
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
|
6 |
+
from tensorflow.keras.preprocessing import image
|
7 |
+
|
8 |
+
# Load the pre-trained MobileNetV2 model for feature extraction
|
9 |
+
model = MobileNetV2(weights='imagenet', include_top=False, pooling='avg')
|
10 |
+
|
11 |
+
def preprocess_image(img):
|
12 |
+
"""Preprocess the image to fit MobileNetV2 requirements"""
|
13 |
+
img = img.resize((224, 224)) # Resize the image to 224x224
|
14 |
+
img_array = image.img_to_array(img) # Convert to numpy array
|
15 |
+
img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
|
16 |
+
return preprocess_input(img_array) # Preprocess the image
|
17 |
+
|
18 |
+
def compare_images(image1, image2):
|
19 |
+
"""Compare two images using cosine similarity of their features"""
|
20 |
+
# Extract features for both images
|
21 |
+
features1 = model.predict(preprocess_image(image1))
|
22 |
+
features2 = model.predict(preprocess_image(image2))
|
23 |
+
|
24 |
+
# Compute cosine similarity between features
|
25 |
+
similarity = np.dot(features1, features2.T)
|
26 |
+
similarity = similarity / (np.linalg.norm(features1) * np.linalg.norm(features2))
|
27 |
+
return {'Similarity': float(similarity)}
|
28 |
+
|
29 |
+
# Setup Gradio interface
|
30 |
+
iface = gr.Interface(
|
31 |
+
fn=compare_images,
|
32 |
+
inputs=[gr.inputs.Image(shape=None), gr.inputs.Image(shape=None)],
|
33 |
+
outputs=[gr.outputs.Label(num_top_classes=1)],
|
34 |
+
title="Image Similarity Checker",
|
35 |
+
description="Upload two images to compare their similarity based on extracted features using MobileNetV2."
|
36 |
+
)
|
37 |
+
|
38 |
+
if __name__ == "__main__":
|
39 |
+
iface.launch()
|