Skip to content

Instantly share code, notes, and snippets.

@Park-Developer
Created April 13, 2021 15:27
Show Gist options
  • Save Park-Developer/d45c801590fa5d220b8ad063b92a2dd1 to your computer and use it in GitHub Desktop.
Save Park-Developer/d45c801590fa5d220b8ad063b92a2dd1 to your computer and use it in GitHub Desktop.
OpenCV : hash matching
import cv2
import numpy as np
import glob
# 영상 읽기 및 표시
img = cv2.imread('pistol.jpg')
cv2.imshow('query', img)
# 비교할 영상들이 있는 경로
search_dir ="101_ObjectCategories"
# 이미지를 16X16 크기의 평균 해시로 변환
def img2hash(img):
gray= cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray= cv2.resize(gray, (16,16))
avg = gray.mean()
bi = 1 *(gray > avg)
return bi
# 해밍 거리로 측정 함수
def hamming_distance(a,b):
a=a.reshape(1,-1) # 이거 뭔뜻임?
b=b.reshape(1,-1)
# 같은 자리의 값이 서로 다른 것들의 합
distance = (a !=b).sum()
return distance
# 권총 영상에서 해시 구하기
query_hash = img2hash(img)
# 이미지 데이터셋 디렉터리의 모든 영상 파일 경로
img_path = glob.glob(search_dir+'/**/*.jpg')
for path in img_path:
# 데이터셋 영상 한 개를 읽어서 표시
img = cv2.imread(path)
cv2.imshow('Searching...' , img)
cv2.waitKey(5)
# 데이터셋 영상 한 개의 해시
a_hash = img2hash(img)
# 해밍 거리 산출
dst = hamming_distance(query_hash , a_hash)
if dst/256 < 0.25: # 해밍거리25% 이내만 출력
print(path, dst/256)
cv2.imshow(path,img)
cv2.destroyWindow('Searching...')
cv2.waitKey(0)
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment