-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage_search.py
83 lines (64 loc) · 2.45 KB
/
image_search.py
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
import numpy as np
import pickle
import random
import requests
from keras.models import load_model
from keras.preprocessing.image import image_utils
from keras.applications.resnet import preprocess_input
from sklearn.preprocessing import LabelEncoder
from io import BytesIO
import mysql.connector
# Database credentials
user = "root"
password = "0705"
database = "fashonApp"
# Model Loading
model = load_model('my_model.h5')
# Load Label Encoder
with open('label_encoder.pkl', 'rb') as f:
label_encoder = pickle.load(f)
def predict_category(image_url):
# Load and preprocess image from url
response = requests.get(image_url)
image = image_utils.load_img(BytesIO(response.content), target_size=(224, 224))
image = image_utils.img_to_array(image)
image = preprocess_input(image)
# Create image batch
image = np.expand_dims(image, axis=0)
# Predict category
prediction = model.predict(image)
# Get category index with highest probability
category_index = np.argmax(prediction)
# Convert category index to label
category = label_encoder.inverse_transform([category_index])[0]
return category
def get_products_from_category(category, image_url):
# Connect to DB
mydb = mysql.connector.connect(
host="localhost",
user=user,
password=password,
database=database
)
mycursor = mydb.cursor()
# Check if the image url exists in the database
mycursor.execute(f"SELECT * FROM product_info WHERE image_link = '{image_url}'")
exact_match = mycursor.fetchone()
# If exact match found, print it
if exact_match:
print('Exact match:', exact_match)
# Execute SQL query to get products from predicted category
mycursor.execute(f"SELECT * FROM product_info WHERE image_link != '{image_url}' AND id IN (SELECT pi.id FROM product_info pi JOIN predicted_categories pc ON pi.image_link = pc.image_link WHERE pc.category = '{category}')")
# Fetch all products
products = mycursor.fetchall()
# Select 10 random products
random_products = random.sample(products, min(10, len(products)))
return random_products
# Predict category for given image url
image_url = input("Enter the image URL: ")
predicted_category = predict_category(image_url)
print('Predicted category:', predicted_category)
# Fetch 10 random products from the predicted category
products = get_products_from_category(predicted_category, image_url)
for product in products:
print(product)