news_verification / src /application /image /image_comparison.py
pmkhanh7890's picture
complete the 1st version of GUI
da7dbd0
raw
history blame
2.18 kB
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