Skip to content

Instantly share code, notes, and snippets.

@miettal
Created October 6, 2015 02:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miettal/47616cff87ab14c0a105 to your computer and use it in GitHub Desktop.
Save miettal/47616cff87ab14c0a105 to your computer and use it in GitHub Desktop.
analysis.py
#!/usr/bin/env python
# coding:utf-8
#
# analysis.py
#
# Author: Hiromasa Ihara (miettal)
# Created: 2015-10-04
#
import os.path
import cv2
def analysis(filename) :
im = cv2.imread(filename)
#グレースケール化
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
cv2.imwrite(filename+'_00gray.png', im_gray)
#ヒストグラムの作成
hist = cv2.calcHist([im_gray],[0],None,[256],[0,256])
sorthist = sorted(list(enumerate(hist)), key=lambda x:-x[1])
#テンプレート画像の読み込み
im_templates = {}
for filename_ in os.listdir('template') :
if filename_ == ".DS_Store" : continue
imt = cv2.imread("template/"+filename_, 1)
imt = cv2.cvtColor(imt, cv2.COLOR_BGR2GRAY)
im_templates[filename_[0]] = imt
#ヒストグラムを元に、二値化のためのしきい値ぎめ
if sorthist[0][0] < sorthist[2][0] :
s = sorthist[2][0]-5
else :
s = sorthist[2][0]+5
#二値化
blur = cv2.bilateralFilter(im_gray, 6, 12, 3)
_,im_mono = cv2.threshold(blur, s, 255, cv2.THRESH_BINARY_INV)
cv2.imwrite(filename+'_01mono.png', im_mono)
matchs = []
#各テンプレート画像とマッチング
im_result= im_mono.copy()
for (c, im_template) in im_templates.items() :
(h, w) = im_template.shape
ms = cv2.matchTemplate(im_template, im_mono, cv2.TM_CCOEFF_NORMED)
for y in xrange(ms.shape[0]):
for x in xrange(ms.shape[1]):
if 0.8 < ms[y][x] :
rect_1 = (x, y)
rect_2 = (x + w, y + h)
cv2.rectangle(im_result, rect_1, rect_2, 0x00)
flag = False
for match in matchs :
if match['loc'][0]-5 < x < match['loc'][0]+5 :
flag = True
if flag == True :
continue
matchs.append({'c': c, 'loc':(x, y)})
#print "({0}, {1}) score = {2}\n".format(maxloc[0], maxloc[1], maxval)
cv2.imwrite(filename+'_02result.png', im_result)
#マッチング画像を座標順にソート
result = ''.join([x['c'] for x in sorted(matchs, key=lambda x:x['loc'][0])])
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment