-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
101 lines (83 loc) ยท 3.21 KB
/
app.py
File metadata and controls
101 lines (83 loc) ยท 3.21 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import streamlit as st
from PIL import Image
import torch
from transformers import CLIPProcessor, CLIPModel
from torchvision import transforms
import os
from sklearn.metrics.pairwise import cosine_similarity
# --- Load CLIP ---
@st.cache_resource
def load_clip_model():
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
return model, processor
st.markdown(
"""
<h1 style="
background: linear-gradient(to right, red, orange, red);
-webkit-background-clip: text;
color: transparent;
font-size: 3rem;
text-align: center;
padding: 1rem 0;
">
๐ฌ๏ธ Find Similar Image From Gallery
</h1>
""",
unsafe_allow_html=True
)
model, processor = load_clip_model()
# Dummy Gallery Images (upload some manually or simulate here)
st.markdown("### ๐น Upload some Gallery Images:")
gallery_images = st.file_uploader("Upload many", type=["jpg", "png"], accept_multiple_files=True)
# --- Upload and Compare ---
st.markdown("### ๐น Query:")
uploaded_image = st.file_uploader("Upload one", type=["jpg", "png", "jpeg"])
with st.expander("โ ๏ธ Technology Used โ ๏ธ ", expanded=False):
st.markdown("""
**๐ Upload a query image and find the most similar images from your gallery using CLIP!**
---
### ๐ ๏ธ Technology Used:
- ๐ง CLIP (Contrastive LanguageโImage Pretraining)
- ๐ Cosine Similarity (scikit-learn)
- ๐จ PIL (Image Processing)
- ๐ผ๏ธ Streamlit File Upload + Display
- ๐ Transformers (Hugging Face)
- ๐งฎ PyTorch + TorchVision
---
### โ
Example Use Cases:
- *"Find similar product images."*
- *"Match uploaded screenshot with gallery."*
- *"Reverse visual search from a dataset."*
---
### โ ๏ธ Notes:
- Works best when gallery images are visually distinct.
- Results are based on visual feature similarity, not file names.
""")
gallery_dir = "gallery"
os.makedirs(gallery_dir, exist_ok=True)
for img in gallery_images:
with open(os.path.join(gallery_dir, img.name), "wb") as f:
f.write(img.read())
def get_embedding(image):
inputs = processor(images=image, return_tensors="pt")
with torch.no_grad():
embedding = model.get_image_features(**inputs)
return embedding
if uploaded_image and gallery_images:
query_img = Image.open(uploaded_image).convert("RGB")
query_embedding = get_embedding(query_img)
similarities = []
for file in os.listdir(gallery_dir):
path = os.path.join(gallery_dir, file)
img = Image.open(path).convert("RGB")
emb = get_embedding(img)
score = cosine_similarity(query_embedding, emb)[0][0]
similarities.append((file, score))
similarities.sort(key=lambda x: x[1], reverse=True)
top_matches = similarities[:3]
st.image(query_img, caption="Query Image", use_container_width=True)
st.markdown("### ๐ Top 3 Matches (with scores):")
for filename, score in top_matches:
img = Image.open(os.path.join(gallery_dir, filename)).convert("RGB")
st.image(img, caption=f"{filename} (Score: {score:.2f})", use_container_width=True)