import gradio as gr import cv2 import numpy as np from skimage.metrics import structural_similarity as ssim def preprocess_image(image): # Convert to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Apply Gaussian blur to reduce noise blurred = cv2.GaussianBlur(gray, (5, 5), 0) return blurred def compare_images(image1, image2): # Preprocess images gray1 = preprocess_image(image1) gray2 = preprocess_image(image2) # Compute SSIM between the two images score, diff = ssim(gray1, gray2, full=True) diff = (diff * 255).astype("uint8") # Apply adaptive thresholding for better object isolation _, thresh = cv2.threshold(diff, 30, 255, cv2.THRESH_BINARY_INV) # Find contours of differences contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Filter out small noise using contour area threshold filtered_contours = [cnt for cnt in contours if cv2.contourArea(cnt) > 500] # Create a mask to isolate only the significant added object mask = np.zeros_like(image1) cv2.drawContours(mask, filtered_contours, -1, (255, 255, 255), thickness=cv2.FILLED) # Apply the mask to highlight the object added in the second image highlighted = cv2.bitwise_and(image2, mask) return highlighted demo = gr.Interface( fn=compare_images, inputs=[ gr.Image(type="numpy", label="Image Without Object"), gr.Image(type="numpy", label="Image With Object") ], outputs=gr.Image(type="numpy", label="Highlighted Differences"), title="Object Difference Highlighter", description="Upload two images: one without an object and one with an object. The app will highlight only the newly added object." ) demo.launch()