@AnteFil

Как решить проблему с написанием цикла обработки?

Есть вот такой код который берет все изображения в папке и сравнивает все между собой.
from sentence_transformers import SentenceTransformer, util
from PIL import Image
import glob
import os
# Load the OpenAI CLIP Model
print('Loading CLIP Model...')
model = SentenceTransformer('clip-ViT-B-32')
# Next we compute the embeddings
# To encode an image, you can use the following code:
# from PIL import Image
# encoded_image = model.encode(Image.open(filepath))
image_names = list(glob.glob('./*.jpg'))
print("Images:", len(image_names))
encoded_image = model.encode([Image.open(filepath) for filepath in image_names], batch_size=128, convert_to_tensor=True, show_progress_bar=True)
# Now we run the clustering algorithm. This function compares images aganist 
# all other images and returns a list with the pairs that have the highest 
# cosine similarity score
processed_images = util.paraphrase_mining_embeddings(encoded_image)
NUM_SIMILAR_IMAGES = 10 
# =================
# DUPLICATES
# =================
print('Finding duplicate images...')
# Filter list for duplicates. Results are triplets (score, image_id1, image_id2) and is scorted in decreasing order
# A duplicate image will have a score of 1.00
# It may be 0.9999 due to lossy image compression (.jpg)
duplicates = [image for image in processed_images if image[0] >= 0.999]
# Output the top X duplicate images
for score, image_id1, image_id2 in duplicates[0:NUM_SIMILAR_IMAGES]:
    print("\nScore: {:.3f}%".format(score * 100))
    print(image_names[image_id1])
    print(image_names[image_id2])
# =================
# NEAR DUPLICATES
# =================
print('Finding near duplicate images...')
# Use a threshold parameter to identify two images as similar. By setting the threshold lower, 
# you will get larger clusters which have less similar images in it. Threshold 0 - 1.00
# A threshold of 1.00 means the two images are exactly the same. Since we are finding near 
# duplicate images, we can set it at 0.99 or any number 0 < X < 1.00.
threshold = 0.99
near_duplicates = [image for image in processed_images if image[0] < threshold]
for score, image_id1, image_id2 in near_duplicates[0:NUM_SIMILAR_IMAGES]:
    print("\nScore: {:.3f}%".format(score * 100))
    print(image_names[image_id1])
    print(image_names[image_id2])

Мне нужно что бы один файл сравнивался со всеми остальными. Мои познания не очень по этому я только с помощью гугл пишу. Нагуглил вот
Открываю пути к изображениям из файла
filename = "massiv_img.txt"
# Открываем файл для чтения
with open(filename, "r") as f:
    # Считываем все строки из файла и сохраняем их в список
    image_names = [line.rstrip() for line in f]

Я создал список затем получаю изображение которое нужно сравнить
query_image = Image.open('2323.jpg')
Дальше не могу ни чего на гуглить помогите пожалуйста

Вот здесь затуп. Должно быть что то вроде такого
Картинка №1 сравнивается с Картинкой №2 итог сходство 10%
Картинка №1 сравнивается с Картинкой №3 итог сходство 10%
Картинка №1 сравнивается с Картинкой №4 итог сходство 10%
Картинка №1 сравнивается с Картинкой №5 итог сходство 10%
Картинка №1 сравнивается с Картинкой №6 итог сходство 10%

.............
Вот так должно быть
  • Вопрос задан
  • 76 просмотров
Пригласить эксперта
Ответы на вопрос 2
phaggi
@phaggi Куратор тега Python
лужу, паяю, ЭВМы починяю
Сравнивать файлы проще всего по hash. Совпали - одинаковые, не совпали - не одинаковые. Поищите, как считать md5, это встроенная в python функция; затем просто вычислите hash для целевого файла и для каждого сравниваемого - и если hash совпали - одинаковые файлы.
Ответ написан
@AnteFil Автор вопроса
Мне надо цикл просто изменить!
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы