import streamlit as st import cv2 from PIL import Image, ImageEnhance import numpy as np import time from skimage.metrics import structural_similarity as ssim import base64 from datetime import datetime import torch # Load pre-trained YOLOv5 model for object detection @st.cache_resource def load_yolo_model(): model = torch.hub.load('ultralytics/yolov5', 'yolov5s') return model def load_css(): st.markdown(""" """, unsafe_allow_html=True) def enhance_image(image): """ Basic image enhancement with default settings """ enhancer = ImageEnhance.Brightness(image) image = enhancer.enhance(1.0) enhancer = ImageEnhance.Contrast(image) image = enhancer.enhance(1.0) enhancer = ImageEnhance.Sharpness(image) image = enhancer.enhance(1.0) return image def compare_images(img1, img2, progress_bar): """ Compare two images and return the processed image, similarity score, and difference percentage """ try: progress_bar.progress(0) # Convert images to numpy arrays and ensure same size img1 = np.array(img1.resize(img2.size)) img2 = np.array(img2) progress_bar.progress(20) # Normalize images img1 = cv2.normalize(img1, None, 0, 255, cv2.NORM_MINMAX) img2 = cv2.normalize(img2, None, 0, 255, cv2.NORM_MINMAX) # Convert to grayscale gray1 = cv2.cvtColor(img1, cv2.COLOR_RGB2GRAY) gray2 = cv2.cvtColor(img2, cv2.COLOR_RGB2GRAY) progress_bar.progress(40) # Calculate SSIM score, diff = ssim(gray1, gray2, full=True) progress_bar.progress(60) # Generate heatmap diff = (diff * 255).astype(np.uint8) heatmap = cv2.applyColorMap(diff, cv2.COLORMAP_JET) progress_bar.progress(80) # Highlight differences in red color diff_mask = cv2.absdiff(gray1, gray2) diff_mask = cv2.cvtColor(diff_mask, cv2.COLOR_GRAY2RGB) diff_mask[np.where((diff_mask == [255, 255, 255]).all(axis=2))] = [0, 0, 255] # Red color for differences # Combine original image with difference mask result_img = cv2.addWeighted(img1, 0.7, diff_mask, 0.3, 0) # Calculate pixel-wise differences diff_percentage = (np.count_nonzero(diff_mask[:, :, 2] > 0) / (diff_mask.shape[0] * diff_mask.shape[1])) * 100 # Ensure that the difference percentage is consistent with the similarity score diff_percentage = 100 - (score * 100) progress_bar.progress(100) return result_img, score, diff_percentage, heatmap except Exception as e: st.error(f"Error comparing images: {str(e)}") return None, 0, 0, None def detect_objects(image, model): """ Perform object detection on the image using YOLOv5 """ try: results = model(image) results_df = results.pandas().xyxy[0] return results_df except Exception as e: st.error(f"Error in object detection: {str(e)}") return None def draw_object_boxes(image, objects_df): """ Draw bounding boxes on the image for detected objects """ for _, row in objects_df.iterrows(): xmin, ymin, xmax, ymax, confidence, class_name = int(row['xmin']), int(row['ymin']), int(row['xmax']), int(row['ymax']), row['confidence'], row['name'] # Draw bounding box cv2.rectangle(image, (xmin, ymin), (xmax, ymax), (0, 255, 0), 2) # Add label cv2.putText(image, f"{class_name} {confidence:.2f}", (xmin, ymin - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2) return image def main(): load_css() # Initialize session state for results if "results" not in st.session_state: st.session_state.results = None # Load YOLOv5 model yolo_model = load_yolo_model() # App header st.markdown("""
Compare images, highlight differences, and detect objects
Built with ❤️ using Streamlit | Last updated: December 2024
Image Comparison Tool v1.0