Spaces:
Running
Running
File size: 2,184 Bytes
da7dbd0 |
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 |
import requests
from io import BytesIO
from PIL import Image
import imagehash
from src.application.image.search_yandex import YandexReverseImageSearcher
def get_image_from_url(url):
try:
response = requests.get(url)
return Image.open(BytesIO(response.content))
except Exception as e:
print(f"Error opening image: {e}")
return None
def get_image_from_file(file_path):
try:
return Image.open(file_path)
except FileNotFoundError:
print(f"Error occurred while opening image from file: {file_path}")
return None
def standardize_image(image):
# Convert to RGB if needed
if image.mode in ('RGBA', 'LA'):
background = Image.new('RGB', image.size, (255, 255, 255))
background.paste(image, mask=image.split()[-1])
image = background
elif image.mode != 'RGB':
image = image.convert('RGB')
# Resize to standard size (e.g. 256x256)
standard_size = (256, 256)
image = image.resize(standard_size)
return image
def compare_images(image1, image2):
# Standardize both images first
img1_std = standardize_image(image1)
img2_std = standardize_image(image2)
hash1 = imagehash.average_hash(img1_std)
hash2 = imagehash.average_hash(img2_std)
return hash1 - hash2 # Returns the Hamming distance between the hashes
if __name__ == '__main__':
image_url = 'https://i.pinimg.com/originals/c4/50/35/c450352ac6ea8645ead206721673e8fb.png'
# Get the image from URL
url_image = get_image_from_url(image_url)
# Search image
rev_img_searcher = YandexReverseImageSearcher()
res = rev_img_searcher.search(image_url)
for search_item in res:
print(f'Title: {search_item.page_title}')
# print(f'Site: {search_item.page_url}')
print(f'Img: {search_item.image_url}\n')
# Compare each search result image with the input image
result_image = get_image_from_url(search_item.image_url)
result_difference = compare_images(result_image, url_image)
print(f"Difference with search result: {result_difference}")
if result_difference == 0:
break |