Path: blob/master/Model-1/WordClassDM.py
427 views
"""1Last: 506923Script with simple UI for creating gaplines data4Run: python WordClassDM.py --index 05Controls:6setting gaplines - click and drag7saving gaplines - 's' key8reseting gaplines - 'r' key9skip to next img - 'n' key10delete last line - 'd' key11"""1213import cv214import os15import numpy as np16import glob17import argparse18import simplejson19from ocr.normalization import imageNorm20from ocr.viz import printProgressBar212223def loadImages(dataloc, idx=0, num=None):24""" Load images and labels """25print("Loading words...")2627dataloc += '/' if dataloc[-1] != '/' else ''28# Load images and short them from the oldest to the newest29imglist = glob.glob(os.path.join(dataloc, u'*.jpg'))30imglist.sort(key=lambda x: float(x.split("_")[-1][:-4]))31tmpLabels = [name[len(dataloc):] for name in imglist]3233labels = np.array(tmpLabels)34images = np.empty(len(imglist), dtype=object)3536if num is None:37upper = len(imglist)38else:39upper = min(idx + num, len(imglist))40num += idx4142for i, img in enumerate(imglist):43# TODO Speed up loading - Normalization44if i >= idx and i < upper:45images[i] = imageNorm(46cv2.cvtColor(cv2.imread(img), cv2.COLOR_BGR2RGB),47height=60,48border=False,49tilt=True,50hystNorm=True)51printProgressBar(i-idx, upper-idx-1)52print()53return (images[idx:num], labels[idx:num])545556class Cycler:57drawing = False58scaleF = 45960def __init__(self, idx, loc='data/words_raw'):61""" Load images and starts from given index """62# self.images, self.labels = loadImages(loc, idx)63self.loc = loc64self.idx = 065self.org_idx = idx6667self.blockLoad()68self.image_act = self.images[self.idx]6970cv2.namedWindow('image')71cv2.setMouseCallback('image', self.mouseHandler)72self.nextImage()7374self.run()7576def run(self):77while(1):78self.imageShow()79k = cv2.waitKey(1) & 0xFF80if k == ord('d'):81# Delete last line82self.deleteLastLine()83elif k == ord('r'):84# Clear current gaplines85self.nextImage()86elif k == ord('s'):87# Save gaplines with image88if self.saveData():89self.idx += 190if self.idx >= len(self.images):91if not self.blockLoad():92break93self.nextImage()94elif k == ord('n'):95# Skip to next image96self.idx += 197if self.idx >= len(self.images):98if not self.blockLoad():99break100self.nextImage()101elif k == 27:102cv2.destroyAllWindows()103break104105print("End of labeling at INDEX: " + str(self.org_idx + self.idx))106107def blockLoad(self):108self.images, self.labels = loadImages(109self.loc, self.org_idx + self.idx, 100)110self.org_idx += self.idx111self.idx = 0112return len(self.images) is not 0113114def imageShow(self):115cv2.imshow(116'image',117cv2.resize(118self.image_act,119(0,0),120fx=self.scaleF,121fy=self.scaleF,122interpolation=cv2.INTERSECT_NONE))123124def nextImage(self):125self.image_act = cv2.cvtColor(self.images[self.idx], cv2.COLOR_GRAY2RGB)126self.label_act = self.labels[self.idx][:-4]127self.gaplines = [0, self.image_act.shape[1]]128self.redrawLines()129130print(self.org_idx + self.idx, ":", self.label_act.split("_")[0])131self.imageShow();132133def saveData(self):134self.gaplines.sort()135print("Saving image with gaplines: ", self.gaplines)136137try:138assert len(self.gaplines) - 1 == len(self.label_act.split("_")[0])139140cv2.imwrite(141"data/words2/%s.jpg" % (self.label_act),142self.images[self.idx])143with open('data/words2/%s.txt' % (self.label_act), 'w') as fp:144simplejson.dump(self.gaplines, fp)145return True146except:147print("Wront number of gaplines")148return False149150print()151self.nextImage()152153def deleteLastLine(self):154if len(self.gaplines) > 0:155del self.gaplines[-1]156self.redrawLines()157158def redrawLines(self):159self.image_act = cv2.cvtColor(self.images[self.idx], cv2.COLOR_GRAY2RGB)160for x in self.gaplines:161self.drawLine(x)162163def drawLine(self, x):164cv2.line(165self.image_act, (x, 0), (x, self.image_act.shape[0]), (0,255,0), 1)166167def mouseHandler(self, event, x, y, flags, param):168# Clip x into image width range169x = max(min(self.image_act.shape[1], x // self.scaleF), 0)170171if event == cv2.EVENT_LBUTTONDOWN:172self.drawing = True173self.tmp = self.image_act.copy()174self.drawLine(x)175elif event == cv2.EVENT_MOUSEMOVE:176if self.drawing == True:177self.image_act = self.tmp.copy()178self.drawLine(x)179elif event == cv2.EVENT_LBUTTONUP:180self.drawing = False181if x not in self.gaplines:182self.gaplines.append(x)183self.image_act = self.tmp.copy()184self.drawLine(x)185186187if __name__ == '__main__':188parser = argparse.ArgumentParser(189"Script creating UI for gaplines classification")190parser.add_argument(191"--index",192type=int,193default=0,194help="Index of starting image")195196args = parser.parse_args()197Cycler(args.index)198199200