|
import gradio as gr |
|
import numpy as np |
|
import tensorflow as tf |
|
from tensorflow.keras.applications import MobileNetV2 |
|
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input |
|
from tensorflow.keras.preprocessing import image |
|
|
|
|
|
model = MobileNetV2(weights='imagenet', include_top=False, pooling='avg') |
|
|
|
def preprocess_image(img): |
|
"""Preprocess the image to fit MobileNetV2 requirements""" |
|
img = img.resize((224, 224)) |
|
img_array = image.img_to_array(img) |
|
img_array = np.expand_dims(img_array, axis=0) |
|
return preprocess_input(img_array) |
|
|
|
def compare_images(image1, image2): |
|
"""Compare two images using cosine similarity of their features""" |
|
|
|
features1 = model.predict(preprocess_image(image1)) |
|
features2 = model.predict(preprocess_image(image2)) |
|
|
|
|
|
similarity = np.dot(features1, features2.T) |
|
similarity = similarity / (np.linalg.norm(features1) * np.linalg.norm(features2)) |
|
return {'Similarity': float(similarity)} |
|
|
|
|
|
iface = gr.Interface( |
|
fn=compare_images, |
|
inputs=[gr.inputs.Image(shape=None), gr.inputs.Image(shape=None)], |
|
outputs=[gr.outputs.Label(num_top_classes=1)], |
|
title="Image Similarity Checker", |
|
description="Upload two images to compare their similarity based on extracted features using MobileNetV2." |
|
) |
|
|
|
if __name__ == "__main__": |
|
iface.launch() |