68 lines
2.4 KiB
Python
68 lines
2.4 KiB
Python
import cv2
|
|
import numpy as np
|
|
from requests import get
|
|
import logging
|
|
|
|
# 로거 인스턴스 가져오기
|
|
logger = logging.getLogger('default_logger')
|
|
|
|
def calculate_similarity(img1, img2):
|
|
# 이미지 특징 추출 (ORB)
|
|
orb = cv2.ORB_create()
|
|
kp1, des1 = orb.detectAndCompute(img1, None)
|
|
kp2, des2 = orb.detectAndCompute(img2, None)
|
|
|
|
# 특징 매칭 (BFMatcher)
|
|
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
|
|
matches = bf.match(des1, des2)
|
|
|
|
# 좋은 매칭만 추출
|
|
good_matches = [m for m in matches if m.distance < 0.75]
|
|
|
|
# 연관도 계산
|
|
# similarity = len(good_matches) / len(kp1)
|
|
similarity = len(good_matches) / len(kp2) if len(kp2) > 0 else 0.0
|
|
|
|
return similarity
|
|
|
|
def download_and_process_image(url):
|
|
# 이미지 다운로드
|
|
headers = {
|
|
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36",
|
|
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
|
|
"Accept-Language": "en-US,en;q=0.9",
|
|
"Accept-Encoding": "gzip, deflate, br",
|
|
"DNT": "1", # Do Not Track 요청 헤더 (사용자의 추적을 거부)
|
|
"Connection": "keep-alive",
|
|
"Upgrade-Insecure-Requests": "1", # https로의 업그레이드를 요청
|
|
"Cache-Control": "max-age=0", # 캐시된 콘텐츠를 재사용하지 않도록 요청
|
|
}
|
|
response = get(url, headers=headers)
|
|
|
|
# 이미지 저장
|
|
if response.status_code == 200:
|
|
with open("image.jpg", "wb") as f:
|
|
f.write(response.content)
|
|
return "image.jpg"
|
|
else:
|
|
logger.debug(f"Error downloading image: {url}")
|
|
return None
|
|
|
|
def compare_images(original_img_url, target_img_url):
|
|
# 이미지 다운로드 및 경로 추출
|
|
original_img_path = download_and_process_image(original_img_url)
|
|
target_img_path = download_and_process_image(target_img_url)
|
|
|
|
# 이미지 비교 수행
|
|
if original_img_path and target_img_path:
|
|
similarity = calculate_similarity(original_img_path, target_img_path)
|
|
logger.debug(f"연관도: {similarity}")
|
|
|
|
return similarity
|
|
|
|
# # 예시
|
|
# original_img_url = "https://www.example.com/original.jpg"
|
|
# target_img_url = "https://www.example.com/target.jpg"
|
|
|
|
# compare_images(original_img_url, target_img_url)
|