euidong / SheetMusic

SheetMusic to RealMusic
4 stars 3 forks source link

뒷배경 투명한 템플릿도 template matching #18

Open wjlee0908 opened 5 years ago

wjlee0908 commented 5 years ago

import cv2
import numpy as np
import sys

if len(sys.argv) < 3:
    print 'Usage: python match.py  '
    sys.exit()

template_path = sys.argv[1]
template = cv2.imread(template_path, cv2.IMREAD_UNCHANGED)
channels = cv2.split(template)
zero_channel = np.zeros_like(channels[0])
mask = np.array(channels[3])

image_path = sys.argv[2]
image = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)

mask[channels[3] == 0] = 1
mask[channels[3] == 100] = 0

# transparent_mask = None
# According to http://www.devsplanet.com/question/35658323, we can only use
# cv2.TM_SQDIFF or cv2.TM_CCORR_NORMED
# All methods can be seen here:
# http://docs.opencv.org/2.4/doc/tutorials/imgproc/histograms/template_matching/template_matching.html#which-are-the-matching-methods-available-in-opencv
method = cv2.TM_SQDIFF  # R(x,y) = \sum _{x',y'} (T(x',y')-I(x+x',y+y'))^2 (essentially, sum of squared differences)

transparent_mask = cv2.merge([zero_channel, zero_channel, zero_channel, mask])
result = cv2.matchTemplate(image, template, method, mask=transparent_mask)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
print 'Lowest squared difference WITH mask', min_val

# Now we'll try it without the mask (should give a much larger error)
transparent_mask = None
result = cv2.matchTemplate(image, template, method, mask=transparent_mask)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
print 'Lowest squared difference WITHOUT mask', min_val

https://gist.github.com/MichaelSnowden/2b5ab97322b1e8d1631df59c6a71a0e1 이 코드 쓰면 뒷배경 투명한 파일 템플릿도 template matching 가능해져서 기호 찾는 데 정확도 올라갈 것 같은데 코드 분석 한 번 해 보면 좋을 것 같습니다. 그런데 파이썬 2버전임

wjlee0908 commented 5 years ago

https://docs.opencv.org/3.4/de/da9/tutorial_template_matching.html template masking하는 방법을 찾았다