def calculEdges(image, echo=True): img = image.copy() cntList = [] txtLines = [] conflict = [] rows, cols = img.shape # convert the grayscale image to binary image ret, thresh = cv2.threshold(img, 127, 255, 0) # find contour in the binary image contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) if echo: printLog("nb contours : ", len(contours)) for c in contours: x, y, w, h = cv2.boundingRect(c) line1 = ((0, y), (cols, y)) line2 = ((0, y + h), (cols, y + h)) txtLines.append((line1, line2)) wrDist(h) # img=cv2.rectangle(img,(0,y),(cols,y+h),(0,255,0),2) if echo: printLog("number of lines : ", len(txtLines)) txtLines.sort(key=lambda x: x[0][0][1]) return txtLines
def loadScanners(cls): ScannerObj.listScanners = selectScanners() cls.currentProgress = 10 ScannerObj.nbScanners = len(ScannerObj.listScanners) printLog("nb scanners = ", ScannerObj.nbScanners) if ScannerObj.nbScanners == 0: printLog("No scanners !!") cls.currentProgress = 100 else: ScannerObj.storeScanners(ScannerObj.listScanners)
def selectSettings(scanner): pgList = [] clList = [] tbr = [] res = 0 switch = 0 #or (ln.startswith('Supported page sizes:')) #Problem while opening the scanner HP DeskJet 2130 series TWAIN for line in new_popen( '.\\clscan\\clscan.exe /GetPageSizes /GetColorTypes /GetResolutions /SetScanner "' + scanner + '"'): ln = line.strip() printLog(ln + '\n') if (ln == "") or (ln.startswith('Selected scanner')): continue elif 'Problem while opening the scanner' in ln: ScannerObj.listScanners.remove(scanner) ScannerObj.nbScanners -= 1 break elif (ln.startswith('Supported page sizes:')): switch = 1 elif (ln.startswith('Supported color types:')): switch = 2 elif (ln.startswith('Supported resolutions:')): switch = 3 elif ('not supported' in ln): switch = 0 elif switch == 1: pgList.append(ln) elif switch == 2: clList.append(ln) elif switch == 3: #print("line : ",ln) if 'step' in ln: res = getResolution(ln) else: tbr.append(int(ln.strip())) if len(tbr) > 0: tbr.sort(reverse=True) if tbr[0] > 300: res = 300 else: res = tbr[0] return pgList, clList, res
def onScan(self, event): scn = self.cbScanners.GetValue() pg = self.cbPgs.GetValue() cr = self.cbCls.GetValue() res = self.resolution secureDel("./scanLog.txt", FILE_TYPE) secureDel("./images/ImageScan.tif", FILE_TYPE) cmd = '.\\clscan\\clscan.exe ' cmd += '/SetFileName ".\\images\\ImageScan.tif" ' cmd += '/LogToFile ".\\scanLog.txt" ' cmd += '/SetDeskew ' cmd += '/SetSource Auto ' cmd += '/SetCrop ' cmd += '/SetThreshold "150" ' cmd += '/SetContrast "50" ' cmd += '/SetBrightness "50" ' # cmd+='/ShowUI ' # cmd+='/UseScan2 ' cmd += '/SetDuplex:Y ' cmd += '/SetJpegQuality "100" ' # cmd+='/SetDeskew ' cmd += '/SetResolution "' + str(res) + '" ' if pg != '': cmd += '/SetPageSize "' + pg + '" ' printLog("added :" + pg) else: printLog("not added :" + pg) if cr != '': cmd += '/SetColorType "' + cr + '" ' cmd += '/SetScanner "' + scn + '" ' log = new_popen(cmd) log += new_popen("python AppExec.py -t 0") log += new_popen("python AppExec.py -t 1") #printLog("\n".join(log)) self.scanned = True self.Close()
def set_resolution(filename, new_filename, new_dpi=300): """ set_resolution(filename,new_filename, new_dpi=300) resize the image : filename is the path to the image. new_dpi is the new resolution default is300 new_filename is the path to the result image to save """ # define the x,y scale (default resolution is 300dpi) x_scale = 1.0 y_scale = 1.0 dpi = get_dpi(filename) printLog(dpi, " ", type(dpi)) if dpi[0] > 0: x_scale = dpi[0] / new_dpi if dpi[1] > 0: y_scale = dpi[1] / new_dpi im = Image.open(filename) size = (int(im.width // x_scale), int(im.height // y_scale)) im_resized = im.resize(size, Image.ANTIALIAS) im_resized.save(new_filename, dpi=(new_dpi, new_dpi))
def calcul_centers(image, echo=True): """calculate the center of dots wich are concidered as multiple blobs. the only given parameter is the image return a list of tuple coordinate (x,y) of centers and corresponding list of bounding rect tuple = ((x,y),(w,h))""" img = image.copy() cntList = [] points = [] if len(img.shape) != 2: # convert the image to grayscale img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.bitwise_not(img) # convert the grayscale image to binary image ret, thresh = cv2.threshold(img, 127, 255, 0) # find contour in the binary image contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) #im2, if echo: printLog("number of dots : ", len(contours)) for c in contours: x, y, w, h = cv2.boundingRect(c) cntList.append(((x, y), (w, h))) # calculate moments for each contour try: M = cv2.moments(c) cX = int(M["m10"] / M["m00"]) cY = int(M["m01"] / M["m00"]) except ZeroDivisionError: continue points.append((cX, cY)) return points, cntList
def preProcess(file_name, new_file_name, ksize=(5, 5)): set_resolution(file_name, new_file_name) printLog(get_dpi(new_file_name)) BlurErodeThresh(file_name, ksize)
def main(lang='ar'): # load the list of DotsLines objects listDotsLines = [] with open('dLdata', 'rb') as dLfile: dLUnpickler = pk.Unpickler(dLfile) listDotsLines = dLUnpickler.load() printLog("nb DotsLines obj : ", len(listDotsLines)) # load the dictionary for selected language dicBTX = {} dicNum = {} if lang == "ar": # dicBTX=arabic_btx # dicNum=arabic_num with open('arData', 'rb') as arFile: arUnpickler = pk.Unpickler(arFile) dicBTX = arUnpickler.load() dicNum = arUnpickler.load() printLog("nb arabic dict items : ", len(dicBTX), "++", len(dicNum)) elif lang == "fr": # dicBTX=french_btx # dicNum=french_num with open('frData', 'rb') as frFile: frUnpickler = pk.Unpickler(frFile) dicBTX = frUnpickler.load() dicNum = frUnpickler.load() printLog("nb french dict items : ", len(dicBTX), "++", len(dicNum)) ########################################## elif lang == "en": with open('enData', 'rb') as enFile: enUnpickler = pk.Unpickler(enFile) dicBTX = enUnpickler.load() dicNum = enUnpickler.load() printLog("nb english dict items : ", len(dicBTX), "++", len(dicNum)) #lang="ar" secureDel('cod.txt', FILE_TYPE, False) secureDel('text.txt', FILE_TYPE, False) for dL in listDotsLines: checked = False #toggle var curDic = dicBTX col1 = [] col2 = [] h_lines = dL.h_lines v_lines = dL.v_lines nbL = len(v_lines) for i in range(nbL - 1): cL1 = v_lines[i] cL2 = v_lines[i + 1] xL1 = cL1[0][0] xL2 = cL2[0][0] if (xL2 - xL1) < 36 and not checked: col1 = dL.selectDots(cL1, 0) col2 = dL.selectDots(cL2, 0) cod = codeChar(h_lines, col1, col2) # printLog("cod= ", cod) mcod = 0 if cod != "" and chk(cod): mcod = int(cod.strip()) else: continue if mcod in curDic.keys(): asc = curDic[mcod] for c in asc: dL.textLine += c checked = True else: #if mcod not in curDic.keys(): writeMSG( str(mcod) + "line=" + str(dL.id) + " numcol = " + str(i)) checked = False if lang != "ar": dL.textLine += '?' elif (xL2 - xL1) < 50 and checked: checked = False elif (xL2 - xL1) < 75 and not checked: col1 = dL.selectDots(cL1, 0) col2 = [] cod = codeChar(h_lines, col1, col2) mcod = 0 if cod != "" and chk(cod): mcod = int(cod.strip()) else: continue if mcod in curDic.keys(): asc = curDic[mcod] for c in asc: dL.textLine += c checked = False else: #if mcod not in curDic.keys(): writeMSG( str(mcod) + "line=" + str(dL.id) + " numcol = " + str(i)) checked = False if lang != "ar": dL.textLine += '?' elif (xL2 - xL1) > 78: checked = False dL.textLine += ' ' #printLog(dL.textLine.strip()) with open('text.txt', 'a', encoding='latin-1') as wf: wf.write(dL.textLine.strip() + '\n')
ss += 1 print("Loaded ...", keepGoing) dialog.Close() dialog.Destroy() print("destroyed !!") if __name__ == '__main__': # When this module is run (not imported) then create the app, the # frame, show it, and start the event loop. # The_program_to_hide = win32gui.GetForegroundWindow() # win32gui.ShowWindow(The_program_to_hide , win32con.SW_HIDE) if not adm.isUserAdmin(): printLog("You're not an admin.", os.getpid()) adm.runAsAdmin() sys.exit(0) else: printLog("You are an admin!", os.getpid()) secureDel("./log.txt", FILE_TYPE) app = wx.App(False) # ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 0) # Ask user to login # dlg = LoginDialog() # dlg.ShowModal() # authenticated = dlg.logged_in # dlg.Destroy()
def OnCombo(self, event): self.fillSettings(self.cbScanners.GetValue()) printLog("You selected" + self.cbScanners.GetValue() + " from Combobox")
def main() : nbL=0 secureDel('dist2.txt',FILE_TYPE,False) with open ('nbLines.txt','r') as f : ln=f.read() tab=ln.strip().split(':') nbL=int(tab[1]) printLog("nbL = ", nbL) listDotsLines=[] for i in range(nbL) : HL=[] frmName='./Lines/Line' +str(i+1)+'.jpg' img=cv2.imread(frmName, 0) points=calcul_centers(img,echo=False)[0] rows,cols=img.shape imgName="./Lines/frames/inverted_"+str(i+1)+".jpg" erodInvert(img, ks1=(1,400), ks2=(0,0), invName=imgName) img2=cv2.imread(imgName, 0) # convert the grayscale image to binary image ret,thresh = cv2.threshold(img2, 127, 255, 0) # find contour in the binary image contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) #printLog("nb contours : ",len(contours)) for c in contours : x,y,w,h = cv2.boundingRect(c) y0=int(y+(h//2)) line0=((0,y0),(cols,y0)) HL.append(line0) points2=[] for p in points : yp=selectLine(HL,p,Y_AXIS) points2.append((p[0],yp)) # drawDotsLines(frmName, points2, HL,(i+1)) frmName=drawDotsLines(frmName, points2, None,(i+1)) img1=cv2.imread(frmName,0) # imvName='./Lines/frames/inverted_' +str(i+1)+'.jpg' imgName='./Lines/frames/vertical_' +str(i+1)+'.jpg' # VerticalMask(img1, ks1=(50,1),ks2=(5,1), # invName=imvName,dilName=imgName) erodInvert(img1, ks1=(100,3), ks2=(0,0), invName=imgName) k=cv2.imread(imgName,0) ret,thresh = cv2.threshold(k,127,255,0) contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) #printLog("nb contours : ",len(contours)) v_lines=[] for c in contours : x,y,w,h = cv2.boundingRect(c) xL=int(x+(w//2)) v_lines.append(((xL, 0),(xL, rows))) v_lines.sort() points3=[] for p in points2 : xp=selectLine(v_lines,p,X_AXIS) points3.append((xp,p[1])) frmName=drawDotsLines(frmName, points3, v_lines,(i+1)) dL=DotsLines(i+1, points3, HL, v_lines) listDotsLines.append(dL) writeDist(v_lines,sign="line "+str(i+1)+" : \n") with open('dLdata','wb') as dLfile : dLPickler=pickle.Pickler(dLfile) dLPickler.dump(listDotsLines)