import sys import cv2 import numpy as np import math from os.path import exists, basename from common import image_resize, display, normalize_angle from json import load #clockwise from top left order = [ 0, 2, 3, 5, 4, 1 ] matchMethods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR', 'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED'] def read_text (textPath) : holePunches = {} with open(textPath) as json: holePunches = load(json) return holePunches # # CALIBRATE # if len(sys.argv) < 2: print('Please provide path of normalized scan to calibrate to') exit(1) if len(sys.argv) < 3: print('Please provide path to output svg template') exit(2) normalImage = sys.argv[-2] if not exists(normalImage) : print('Normalized scan does not exist, please provide one that does') exit(2) normalText = normalImage + '.json' if not exists(normalText) : print('Corresponding normalized scan text does not exist, please generate one') exit(3) outputTmpl = sys.argv[-1] print(f'Calibrating to scan {basename(normalImage)}') registrationMark = cv2.imread('./registration_mark.png', 0) w, h = registrationMark.shape[:2] holePunches = read_text(normalText) original = cv2.imread(normalImage) img = original.copy() height, width = img.shape[:2] orientation = height > width if not orientation : print(f'Scan is not in portrait mode, exiting...') exit(3) print(holePunches) topHalf = img[holePunches['0']['y']:holePunches['1']['y']+round(height*0.1), holePunches['0']['x']:holePunches['2']['x']] topHalfGray = cv2.cvtColor(topHalf, cv2.COLOR_BGR2GRAY) res = cv2.matchTemplate(topHalfGray, registrationMark, cv2.TM_CCOEFF_NORMED) threshold = 0.5 loc = np.where( res >= threshold) for pt in zip(*loc[::-1]): print(f'{pt[0]},{pt[1]}') cv2.rectangle(topHalf, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2) display(topHalf)