Image Search Code Working
Image Search Code Working
--------------
--------------
import torch
from transformers import ViTModel, ViTFeatureExtractor
from PIL import Image
import os
import csv
import oracledb
import numpy as np
import array
from tqdm import tqdm
import pandas as pd
# Load pre-trained ViT model and remove the final classification layer
model = ViTModel.from_pretrained('google/vit-base-patch16-224')
model.eval()
--------------
def extract_features(image_path):
image = Image.open(image_path).convert('RGB')
inputs = feature_extractor(images=image, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
# We use the [CLS] token representation as the feature vector
features = outputs.last_hidden_state[:, 0, :].squeeze().numpy()
return features
--------------
--------------
def numpy_converter_in(value):
if value.dtype == np.float64:
dtype = "d"
elif value.dtype == np.float32:
dtype = "f"
else:
dtype = "b"
return array.array(dtype, value)
connection.inputtypehandler = input_type_handler
--------------
!ls -ltr
cd Image_Similarity_Search
ls -ltr
cd imagesearch1-main/
ls -ltr
!unzip Image_Similarity_Search.zip
!pwd
!ls -ltr
---------------
# Function to insert image paths and features into Oracle Database in batch
def batch_insert_into_oracle(image_data):
cursor.executemany("""
INSERT INTO image_features (image_path, feature_vector)
VALUES (:1, :2)
""", image_data)
connection.commit()
image_data = []
---------------
def numpy_converter_out(value):
if value.typecode == "b":
dtype = numpy.int8
elif value.typecode == "f":
dtype = numpy.float32
else:
dtype = numpy.float64
return numpy.array(value, copy=False, dtype=dtype)
---------------
cursor.execute("""
SELECT image_path
FROM image_features
ORDER BY VECTOR_DISTANCE(feature_vector, :query_vector, COSINE)
FETCH FIRST :top_n ROWS ONLY
""", {'query_vector': query_vector, 'top_n': top_n})
results = cursor.fetchall()
return [row[0] for row in results]
---------------
plt.show()
cursor.execute("""
SELECT image_path
FROM image_features
ORDER BY VECTOR_DISTANCE(feature_vector, :query_vector, COSINE)
FETCH FIRST :top_n ROWS ONLY
""", {'query_vector': query_vector, 'top_n': top_n})
results = cursor.fetchall()
similar_image_paths = [row[0] for row in results]
display_images(query_image_path, similar_image_paths)
---------------
---------------