Skip to content
Snippets Groups Projects
Commit 240ebeef authored by Félix Yriarte's avatar Félix Yriarte
Browse files

fix infinite loop

parent 2b5b6526
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
# Packages and general functions
%% Cell type:markdown id: tags:
## Used packages
%% Cell type:code id: tags:
``` python
import math
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import os
from os import listdir
from os.path import isfile, join, splitext
import cv2
from skimage.color import gray2rgb
from skimage.io import imread, imshow, imsave
from skimage.util import invert
from skimage.transform import resize, rotate
from skimage.morphology import erosion, dilation, opening, closing, skeletonize, square
from skimage.filters import threshold_isodata, threshold_li, threshold_mean, threshold_minimum, threshold_otsu, threshold_triangle, threshold_yen
#from sklearn.cluster import KMeans
```
%% Cell type:markdown id: tags:
## Image processing functions
%% Cell type:code id: tags:
``` python
# Load an image using io.imread. Note that morphology functions only work on gray-scale or binary images: set as_gray = True
def load_image(path):
im_gray = imread(path, as_gray=True)
return im_gray
def erosion_image(image, structural_elem = 'None'):
if structural_elem != 'None':
return erosion(image, structural_elem)
else:
return erosion(image)
def dilation_image(image, structural_elem = 'None'):
if structural_elem != 'None':
return dilation(image, structural_elem)
else:
return dilation(image)
def opening_image(image, structural_elem = 'None'):
if structural_elem != 'None':
return opening(image, structural_elem)
else:
return opening(image)
def closing_image(image, structural_elem = 'None'):
if structural_elem != 'None':
return closing(image, structural_elem)
else:
return closing(image)
def skeletonization_image(image_bin, method):
image_bin = invert(image_bin)
if method == "lee":
skel = skeletonize(image_bin, method = "lee")
else:
skel = skeletonize(image_bin, method = "zhang")
return skel
def binarization_image(image, method):
if method == "isodata":
th = threshold_isodata(image)
elif method == "li":
th = threshold_li(image)
elif method == "mean":
th = threshold_mean(image)
elif method == "minimum":
th = threshold_minimum(image)
elif method == "triangle":
th = threshold_triangle(image)
elif method == "yen":
th = threshold_yen(image)
else:
th = threshold_otsu(image)
print("threshold found : "+str(th))
binary =( image > th)
return binary
```
%% Cell type:markdown id: tags:
# FuzzyDoc functions
%% Cell type:code id: tags:
``` python
def euclidean_distance_minutia(m1, m2):
return math.sqrt((m1[0] - m2[0])*(m1[0] - m2[0]) + (m1[1] - m2[1])*(m1[1] - m2[1]))
```
%% Cell type:markdown id: tags:
## P&S character pre-processing
%% Cell type:markdown id: tags:
## Feature extraction
%% Cell type:code id: tags:
``` python
def minutia_extraction(im_skeleton):
minutia = []
h = im_skeleton.shape[0]
w = im_skeleton.shape[1]
for i in range(1, h-1):
for j in range(1, w-1):
if im_skeleton[i][j] !=0:
P = [ im_skeleton[i][j+1], im_skeleton[i-1][j+1], im_skeleton[i-1][j], im_skeleton[i-1][j-1], im_skeleton[i][j-1], im_skeleton[i+1][j-1], im_skeleton[i+1][j], im_skeleton[i+1][j+1], im_skeleton[i][j+1] ]
CN = 0
for k in range(8):
CN += abs(P[k]/255 - P[k+1]/255)
CN = 0.5*CN
# 0 : Isolated point
# 1 : Ending point
# 2 : Connective point
# 3 : Bifurcation point
# 4 : Crossing point
# only consider 0,1,3,4 CN values
if CN==0:
minutia.append((i,j,0))
elif CN == 1:
minutia.append((i,j,1))
elif CN == 3:
minutia.append((i,j,3))
elif CN == 4:
minutia.append((i,j,4))
return minutia
```
%% Cell type:code id: tags:
``` python
def draw_minutia(minutia, im_skeleton):
h = im_skeleton.shape[0]
w = im_skeleton.shape[1]
im_skeleton_color = gray2rgb(im_skeleton)
for m in minutia:
im_skeleton_color[m[0]][m[1]] = (255, 0, 0)
return im_skeleton_color
```
%% Cell type:markdown id: tags:
## Smoothing operation
%% Cell type:code id: tags:
``` python
def smoothing(minutia, threshold):
smooth_minutia = []
ending_points = []
smooth_ending_points = []
pb = []
for m in minutia:
if m[2] != 1:
smooth_minutia.append(m)
else:
ending_points.append(m)
if smooth_minutia == []:
return minutia
else:
for m in ending_points:
i = 0
while (i < len(smooth_minutia)) and (euclidean_distance_minutia(m, smooth_minutia[i]) > threshold):
i = i+1
if (i == len(smooth_minutia)):
smooth_ending_points.append(m)
else:
pb.append(smooth_minutia[i])
pb = list(set(pb))
for m in pb:
smooth_minutia.remove(m)
return smooth_minutia + smooth_ending_points
```
%% Cell type:markdown id: tags:
# Main program
%% Cell type:markdown id: tags:
# Geometric transformation correction
%% Cell type:code id: tags:
``` python
def findCorners(im,struct): #corner detection used to cancel geometric transformations
binPre=binarization_image(im,'otsu')
bin=closing_image(binPre,structural_elem=struct)
#HAUTGAUCHE
cornerHG=[-1,-1]
found=False
dist=0
while not(found):
i=0
while i<=dist and not(found):
x=i
y=dist-i
# if x>=im.shape[0] or y>=im.shape[1]:
# return(-1,-1,-1,-1,-1,-1,-1,-1) HG
if not(bin[x][y]):
found=True
cornerHG=[x,y]
i+=1
dist+=1
#HAUTDROIT
cornerHD=[-1,-1]
found=False
dist=0
while not(found):
i=0
while i<=dist and not(found):
x=dist - i
y=im.shape[1]-1-i
# if x>=im.shape[0] or y>=im.shape[1]:
# return(-1,-1,-1,-1,-1,-1,-1,-1) HD
if not(bin[x][y]):
found=True
cornerHD=[x,y]
i+=1
dist+=1
#BASGAUCHE
cornerBG=[-1,-1]
found=False
dist=0
while not(found):
i=0
while i<=dist and not(found):
x=im.shape[0]-1 - i
y=dist-i
# if x>=im.shape[0] or y>=im.shape[1]:
# return(-1,-1,-1,-1,-1,-1,-1,-1) BG
if not(bin[x][y]):
found=True
cornerBG=[x,y]
i+=1
dist+=1
#BASGAUCHE
cornerBD=[-1,-1]
found=False
dist=0
while not(found):
i=0
while i<=dist and not(found):
x=im.shape[0]-1 - dist + i
y=im.shape[1] - 1 - i
# if x>=im.shape[0] or y>=im.shape[1]:
# return(-1,-1,-1,-1,-1,-1,-1,-1) BD
if not(bin[x][y]):
found=True
cornerBD=[x,y]
i+=1
dist+=1
return(cornerHG[0],cornerBD[0],cornerBG[1],cornerHD[1],cornerHG[1],cornerBD[1],cornerBG[0],cornerHD[0])
def removeTransfos(path,struct): # detect corner, then correct translation and rotation noise
im=load_image(path)
firstBV,lastBV, firstBH, lastBH,firstBVy,lastBVy, firstBHx, lastBHx=findCorners(im,struct)
minus=1.0
ax,cx,dy,by,ay,cy,dx,bx=firstBV,lastBV, firstBH, lastBH,firstBVy,lastBVy, firstBHx, lastBHx
if firstBV>lastBHx:
minus=-1.0
theta1=minus*180/math.pi*math.acos((by-ay)/math.sqrt((bx-ax)*(bx-ax)+(by-ay)*(by-ay))) # A--------B
theta2=minus*180/math.pi*math.acos((cx-bx)/math.sqrt((cx-bx)*(cx-bx)+(by-cy)*(by-cy))) # | |
theta3=minus*180/math.pi*math.acos((cy-dy)/math.sqrt((cx-dx)*(cx-dx)+(cy-dy)*(cy-dy))) # | |
theta4=minus*180/math.pi*math.acos((dx-ax)/math.sqrt((dx-ax)*(dx-ax)+(ay-dy)*(ay-dy))) # D--------C
#rotation angles are estimated
L=[theta1,theta2,theta3,theta4]
for i in range(len(L)):
if L[i]>45.0:
L[i]=L[i] - 90.0
print(theta1,theta2,theta3,theta4, float(sum(L)/float(len(L))))
testIm=rotate(im,float(sum(L)/float(len(L))),mode='constant',resize=True,cval=255,preserve_range=True,center=None)
# the image is rotated
plt.imsave('rotPreCrop.png',testIm)
firstBV,lastBV, firstBH, lastBH,firstBVy,lastBVy, firstBHx, lastBHx=findCorners(testIm,struct)
minX=min(firstBV,lastBHx,lastBV,firstBHx)
maxX=max(firstBV,lastBHx,lastBV,firstBHx)
minY=min(firstBVy,lastBH,lastBVy,firstBH)
maxY=max(firstBVy,lastBH,lastBVy,firstBH)
print(minX,maxX,minY,maxY)
crop=np.zeros((int(maxX-minX),int(maxY-minY)))
# then cropped
for i in range(int(maxX-minX)):
for j in range(int(maxY-minY)):
crop[i][j]=testIm[int(i+minX)][int(j+minY)]
return(crop)
```
%% Cell type:markdown id: tags:
# Dynamic mask detection
%% Cell type:code id: tags:
``` python
def detectTextAreas(path,maskName,struct): # text content detection (spot and table removal)
img = removeTransfos(path,struct)
img = skeletonization_image(binarization_image(img,'otsu'),'lee')
imsave("NoBorders.png",img)
img = cv2.imread("NoBorders.png")
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
out = np.zeros(gray.shape)
# Apply adaptive threshold
#thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)
# Find the contours
contours,hierarchy = cv2.findContours(gray,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
x,y,w,h = cv2.boundingRect(cnt)
if (w > 2 and h > 2 and h < 150 and w < 150): # 5 vs 15 ?
cv2.rectangle(out,(x,y),(x+w,y+h),255,-1)
for i in range(out.shape[0]):
for j in range(out.shape[1]):
if out[i][j] == 255:
k = 1
while j+k < out.shape[1] and out[i][j+k] != 255 and k < 100:
k = k+1
if k < 100 and j+k < out.shape[1]:
out[i][j+1] = 255
cv2.imwrite('contours1.png', out)
out = cv2.imread('contours1.png')
out = cv2.cvtColor(out,cv2.COLOR_BGR2GRAY)
im_out = cv2.imread('NoBorders.png')
im_out = cv2.cvtColor(im_out,cv2.COLOR_BGR2GRAY)
contours,hierarchy = cv2.findContours(out,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(out,(x,y),(x+w,y+h),255,-1)
for i in range(out.shape[0]):
for j in range(out.shape[1]):
im_out[i][j] = im_out[i][j] and out[i][j]
# Finally show the image
cv2.imwrite(maskName, out)
cv2.imwrite('imMask.png', im_out)
return(load_image('imMask.png'))
#detectTextAreas("payslips/Payslip_dataset_P&S/ForgedN1/Numeric/imitation/02_600dpi/Imitation_1_PaySlip_Arial_10_1-f_1.jpg")
```
%% Cell type:markdown id: tags:
# Matching
%% Cell type:code id: tags:
``` python
def fastFindMatch(set1,set2,maxH,maxW): #low computational cost distance based matching function
resCN=[] #
resDist=[] #for all CNs in set1, return the closest CN in set2
spatialLocation=np.full((maxH,maxW),-1)
for cn in range(len(set2)):
spatialLocation[set2[cn][0]][set2[cn][1]]=cn
for cn in set1:
found=False
count=0
while not(found):
tempCN=()
tempDist=float('infinity')
for i in range(-count,count+1,1):
for j in range(-count,count+1,1):
x=cn[0]+i
y=cn[1]+j
if max(abs(i),abs(j))==count and x>=0 and x<maxH and y>=0 and y<maxW:
if spatialLocation[x][y]!=-1:
tempCN=set2[spatialLocation[x][y]]
tempDist=min(tempDist,count)
found=True
if found:
resCN.append(tempCN)
resDist.append(tempDist)
count+=1
return(resDist,resCN)
```
%% Cell type:code id: tags:
``` python
def fastMapCleanPMASK(pathG,pathF,gridX,gridY, thresholdG, thresholdF,struct,name1='maskPaulineG.png',name2='maskPaulineF.png'): #preprocess then matching
#transformation correction and mask detection
imG=removeTransfos(pathG,struct)
imsave("GnoBorders.png",imG)
maskedG=detectTextAreas('GnoBorders.png',name1,struct)
imsave("GMasked.png",maskedG)
imF=removeTransfos(pathF,struct)
imsave("FnoBorders.png",imF)
maskedF=detectTextAreas('FnoBorders.png',name2,struct)
imsave('FMasked.png',maskedF)
#minutia extraction, serifs removal, and scaling correction
minG=minutia_extraction(maskedG)
minG=smoothing(minG,thresholdG)
minFNoScale=minutia_extraction(maskedF)
minF=[]
for i in range(len(minFNoScale)):
minF.append((int(minFNoScale[i][0]*maskedG.shape[0]/maskedF.shape[0]),int(minFNoScale[i][1]*maskedG.shape[1]/maskedF.shape[1]),minFNoScale[i][2]))
minF=smoothing(minF,thresholdF)
#distance computing for both CN sets
distances,correspondingCNs=fastFindMatch(minG,minF,maskedG.shape[0],maskedG.shape[1])
corres=[]
maxRad=50
tab=[]
for i in range(gridX):
tab.append([])
for j in range(gridY):
tab[i].append([])
stepX=maskedG.shape[0]/gridX #imF instead of imG ?
stepY=maskedG.shape[1]/gridY #imF instead of imG ?
for i in range(len(minG)):
tab[int(minG[i][0]//stepX)][int(minG[i][1]//stepY)].append(i)
corres.append(min(maxRad,distances[i]))
moys=np.zeros(maskedG.shape)
maxs=np.zeros(maskedG.shape)
colors=[]
colors2=[]
all=[]
CNs=[]
for i in range(gridX):
colors.append([])
colors2.append([])
for j in range(gridY):
moy=0
maxi=0
for c in range(len(tab[i][j])):
moy+=corres[tab[i][j][c]]/len(tab[i][j])
maxi=max(maxi,corres[tab[i][j][c]])
all.append(corres[tab[i][j][c]])
CNs.append(minG[tab[i][j][c]])
colors[i].append(moy)
colors2[i].append(maxi)
for i in range(maskedG.shape[0]):
for j in range(maskedG.shape[1]):
moys[i][j]=colors[int(i//stepX)][int(j//stepY)]
maxs[i][j]=colors2[int(i//stepX)][int(j//stepY)]
return moys,maxs,all,CNs
```
%% Cell type:markdown id: tags:
# Dispersion analysis
%% Cell type:code id: tags:
``` python
def readMask(mask): #from mask to box set
res=[] #[((xD1,yD1),(xF1,yF1))]
for i in range(mask.shape[0]):
j=0
while j<mask.shape[1]:
flag=False
if mask[i][j]:
for test in range(len(res)):
if i>=res[test][0][0] and i<=res[test][1][0] and j>=res[test][0][1] and j<=res[test][1][1]:
flag=True
if not(flag):
pix=j
pixI=i
while pixI<mask.shape[0] and mask[pixI][j]:
pixI+=1
while pix<mask.shape[1] and mask[i][pix]:
pix+=1
res.append(((i,j),(pixI-1,pix-1)))
j=pix-1
j+=1
return(res)
```
%% Cell type:code id: tags:
``` python
def radiPerBox(listCNs, listRadi, mask): #sort distance values in corresponding mask boxes
posMask=readMask(mask)
res=[]
for i in range(len(posMask)):
res.append([])
for i in range(len(listCNs)):
for box in range(len(posMask)):
if listCNs[i][0]>=posMask[box][0][0] and listCNs[i][0]<=posMask[box][1][0] and listCNs[i][1]>=posMask[box][0][1] and listCNs[i][1]<=posMask[box][1][1]:
res[box].append(listRadi[i])
return res
```
%% Cell type:code id: tags:
``` python
def entropy(dist, max, nbBin): # entropy computing ; dispersion analysis
effObs = np.zeros(nbBin)
for d in dist:
effObs[int(d//(max/nbBin))-1] += 1
res = 0
for e in effObs:
if e != 0:
res += (e / len(dist)) * math.log2((e / len(dist)))
return (-1.0)*res
```
%% Cell type:code id: tags:
``` python
def ecartMoy(listeOccus,maxV,bins=None): #dispersion analysis !! deprecated !!
if bins is None:
bins=maxV+1
res=0.0
hist=np.zeros(bins)
step=(maxV+1)/bins
for i in listeOccus:
hist[int(i//step)]+=1
for i in range(len(hist)):
res+=(hist[i]-len(listeOccus)/maxV)**2
if len(listeOccus)==0:
return 0.0
res/=len(listeOccus)**2
return(res)
```
%% Cell type:markdown id: tags:
# Integrity check
%% Cell type:code id: tags:
``` python
def check(pathG,pathF, thresholdSerifsNUM=5,thresholdSerifsPS=5, thresholdDist=12, thresholdCNNumber=2,thresholdEntropy=0.5,dirOut='./',struct=square(25)):
pathMaskG=dirOut+'maskG.png'
pathMaskF=dirOut+'maskF.png'
moyList,maxList,dist,cn=fastMapCleanPMASK(pathG,pathF,1,1,thresholdSerifsNUM,thresholdSerifsNUM,struct,pathMaskG,pathMaskF)
cnWithoutBorder = []
distWithoutBorder = []
for i in range(len(cn)):
if cn[i][0] > 80 and cn[i][0] < 3219-78:
cnWithoutBorder.append(cn[i])
distWithoutBorder.append(dist[i])
carres=load_image(pathMaskG)
for i in range(carres.shape[0]):
for j in range(carres.shape[1]):
if i < 80 or i > carres.shape[0]-78:
carres[i][j] = 0
ordonnes=radiPerBox(cnWithoutBorder,distWithoutBorder,carres)
maxDist = max(distWithoutBorder)
listG=readMask(carres)
color=[]
flag1=[]
flag2=[]
sortedEntropy=[]
for i in range(len(ordonnes)):
if len(ordonnes[i]) != 0:
color.append(np.mean(ordonnes[i]))
sortedEntropy.append(entropy(ordonnes[i],maxDist,10))
else:
color.append(0)
sortedEntropy.append(0)
count=0
for d in range(len(ordonnes[i])):
if ordonnes[i][d]>=thresholdDist:
count+=1
if count>=thresholdCNNumber:
flag1.append(i)
if entropy(ordonnes[i],maxDist,10)>thresholdEntropy:
flag2.append(i)
mapF=np.zeros(carres.shape)
HmapF=np.zeros(carres.shape)
for i in range(len(listG)):
for pixi in range(listG[i][0][0],listG[i][1][0]+1):
for pixj in range(listG[i][0][1],listG[i][1][1]+1):
mapF[pixi][pixj]=color[i]
HmapF[pixi][pixj]=sortedEntropy[i]
plt.figure(figsize=(30,25))
plt.imshow(mapF,vmin=0.0,vmax=20)
plt.colorbar()
plt.savefig(dirOut+"a-field.png")
plt.figure(figsize=(30,25))
plt.imshow(HmapF,vmin=0.0,vmax=1.0)
plt.colorbar()
plt.savefig(dirOut+"entropy-field.png")
return(flag1,flag2)
```
%% Cell type:markdown id: tags:
# Graph
%% Cell type:code id: tags:
``` python
def indexOfHighestOneMin(mins):
if len(mins)!=0:
anyOne=-1
flag=False
for min in range(len(mins)):
if mins[min][2]==1:
flag=True
anyOne=min
if flag:
highest=mins[anyOne][0]
idx=anyOne
for i in range(len(mins)):
if mins[i][2]==1 and mins[i][0]<highest:
idx=i
highest=mins[idx][0]
return idx
return(-1)
def listSum(a,b):
res =[]
for elem in a:
res.append(elem)
if len(a)==len(b):
for e in range(len(a)) :
res[e]+=b[e]
return res
return
def indexOfHighestThreeMin(mins):
if len(mins)!=0:
anyOne=-1
flag=False
for min in range(len(mins)):
if mins[min][2]==3:
flag=True
anyOne=min
if flag:
highest=mins[anyOne][0]
idx=anyOne
for i in range(len(mins)):
if mins[i][2]==3 and mins[i][0]>highest:
idx=i
highest=mins[idx][0]
return idx
return(-1)
def relativeWhiteDir(skeleton,x,y):
res=[]
for i in [(-1,0),(1,0),(0,1),(0,-1),(-1,-1),(-1,1),(1,-1),(1,1)]:
if skeleton[x+i[0]][y+i[1]]:
res.append(i)
return res
def getPosFromMins(mins):
res=[]
for i in range(len(mins)):
res.append((mins[i][0],mins[i][1]))
return res
def findWhitePix(skel):
for i in range(skel.shape[0]):
for j in range(skel.shape[1]):
if skel[i][j]:
return (i,j)
return(False)
def recurseGraph(skel,mins,depart,posMinDepart):
global debug
global veryDebug
global blocked
visited=[depart]
posMins=getPosFromMins(mins)
nextWhite=relativeWhiteDir(skel,depart[0],depart[1])
flag=False
if debug:
print('pos depart : ',depart,posMins.index(posMinDepart))
if len(nextWhite)==0:
return [(posMins.index(posMinDepart),posMins.index(posMinDepart))],[]
dir=(0,0)
for i in range(len(nextWhite)):
if not((nextWhite[i][0]+depart[0],nextWhite[i][1]+depart[1]) in blocked) and (nextWhite[i][0]+depart[0],nextWhite[i][1]+depart[1])!=posMinDepart:
flag=True
dir=(nextWhite[i][0],nextWhite[i][1])
break
if not(flag):
return [],[]
last=depart
next=(last[0]+dir[0],last[1]+dir[1])
visited.append(next)
while not(next in posMins):
if veryDebug:
print(dir)
nextWhite=relativeWhiteDir(skel,next[0],next[1])
last=next
for i in range(len(nextWhite)):
if not(nextWhite[i]==(-dir[0],-dir[1])):
dir=(nextWhite[i][0],nextWhite[i][1])
break
next=(last[0]+dir[0],last[1]+dir[1])
visited.append(next)
blocked.append(last)
if debug:
print('blocked :',blocked,'point arrivee :',posMins.index(next))
res=[]
res.append((posMins.index(posMinDepart),posMins.index(next)))
nextWhite=relativeWhiteDir(skel,next[0],next[1])
for i in range(len(nextWhite)):
if not((next[0]+nextWhite[i][0],next[1]+nextWhite[i][1]) in blocked) and not((next[0]+nextWhite[i][0],next[1]+nextWhite[i][1])==last):
curr=(next[0]+nextWhite[i][0],next[1]+nextWhite[i][1])
blocked.append((next[0]+nextWhite[i][0],next[1]+nextWhite[i][1]))
childList,visitedChildren=recurseGraph(skel,mins,(next[0]+nextWhite[i][0],next[1]+nextWhite[i][1]),(next[0],next[1]))
for child in childList:
res.append(child)
for i in visitedChildren:
visited.append(i)
return res,visited
```
%% Cell type:code id: tags:
``` python
def graph(path):
im=load_image(path)
skel=skeletonization_image(binarization_image(im,'otsu'),'lee')
skel2=skeletonization_image(binarization_image(im,'otsu'),'lee')
CNs=minutia_extraction(skel)
plt.imsave("rightops.png",draw_minutia(CNs,skel))
global blocked
global debug
global veryDebug
blocked=[]
global encounteredCNs
global nonEncountered
encounteredCNs=[]
nonEncountered=[]
for i in range(len(CNs)):
nonEncountered.append(CNs[i])
tot=[]
count=0
while len(nonEncountered)!=0 or findWhitePix(skel2):
print(findWhitePix(skel2))
if count>50:
while findWhitePix(skel2):
#print(findWhitePix(skel2))
if count>5000:
return tot
idx=indexOfHighestOneMin(nonEncountered)
print(idx)
#print(idx)
if idx<0:
idx=indexOfHighestThreeMin(nonEncountered)
#print('3 ! : '+idx)
if idx<0:
print('loooooop')
#print('loooooop')
a=findWhitePix(skel2)
if a:
nonEncountered.append((a[0],a[1],5))
CNs.append((a[0],a[1],5))
idx=0
compCon,visited=recurseGraph(skel,nonEncountered,(nonEncountered[idx][0],nonEncountered[idx][1]),(nonEncountered[idx][0],nonEncountered[idx][1]))
dot=CNs[CNs.index(nonEncountered[idx])]
compCon,visited=recurseGraph(skel,CNs,(dot[0],dot[1]),(dot[0],dot[1]))
for i in range(len(compCon)):
if not(nonEncountered[compCon[i][0]] in encounteredCNs):
encounteredCNs.append(nonEncountered[compCon[i][0]])
if not(nonEncountered[compCon[i][1]] in encounteredCNs):
encounteredCNs.append(nonEncountered[compCon[i][1]])
if not(CNs[compCon[i][0]] in encounteredCNs):
encounteredCNs.append(CNs[compCon[i][0]])
if not(CNs[compCon[i][1]] in encounteredCNs):
encounteredCNs.append(CNs[compCon[i][1]])
# if (compCon[i][0] in nonEncountered):
# encounteredCNs.append(nonEncountered[compCon[i][0]])
# nonEncountered.remove(compCon[i][0])
# if (compCon[i][1] in nonEncountered):
# encounteredCNs.append(nonEncountered[compCon[i][1]])
# nonEncountered.remove(compCon[i][1])
for i in range(len(encounteredCNs)):
if encounteredCNs[i] in nonEncountered:
nonEncountered.remove(encounteredCNs[i])
for i in range(len(visited)):
skel2[visited[i][0]][visited[i][1]]=False
plt.imshow(skel2)
tot.append(compCon)
count+=1
print(count)
#print(nonEncountered)
#imshow()
plt.imsave('/home/felix/Documents/work/FuzzyDoc/fuzzydoc/hole_skel.png',skel2)
return(tot)
```
%% Cell type:code id: tags:
``` python
path="/home/felix/Documents/work/FuzzyDoc/fuzzydoc/imgs/1_truth.png"
im=load_image(path)
skel=skeletonization_image(binarization_image(im,'otsu'),'lee')
cn=minutia_extraction(skel)
print(cn)
idx=indexOfHighestOneMin(cn)
print(idx)
debug=True ; veryDebug=True ; blocked=[]
print(recurseGraph(skel,cn,(cn[0][0],cn[0][1]),(cn[0][0],cn[0][1]))[0])
```
%% Cell type:code id: tags:
``` python
indexOfHighestOneMin([])
```
debug=False ; veryDebug=False ; blocked=[]
%% Output
-1
print(graph("imMaskINV.png"))
```
%% Cell type:code id: tags:
``` python
path="/home/felix/Documents/work/FuzzyDoc/fuzzydoc/imgs/1_truth.png"
# path="/home/felix/Documents/work/FuzzyDoc/fuzzydoc/imgs/1_truth.png"
path="/home/felix/Documents/work/FuzzyDoc/fuzzydoc/0Dot.jpg"
plt.imshow(skeletonization_image(binarization_image(load_image(path),'otsu'),'lee'))
debug=True ; veryDebug=True ; blocked=[]
# path="/home/felix/Documents/work/FuzzyDoc/fuzzydoc/imgs/new_database/Bounding_Box/Arial_600/num/8/591.jpg"
# path="/home/felix/Documents/work/FuzzyDoc/fuzzydoc/testCadre.png"
# path="/home/felix/Documents/work/FuzzyDoc/fuzzydoc/payslip_Arial_10_1_g.png"
# path="/home/felix/Documents/work/FuzzyDoc/fuzzydoc/imgs/new_database/documents/2PS_Arial_600.jpg"
# mask=detectTextAreas(path,'mask.png',square(25))
# im=load_image(path)
# for i in range(im.shape[0]):
# for j in range(im.shape[1]):
# if not(mask[i][j]):
# im[i][j]=255
# # plt.imshow(skeletonization_image(binarization_image(load_image(path),'otsu'),'lee'))
# newpath="imClean.png"
# plt.imsave(newpath,im)
debug=False ; veryDebug=False ; blocked=[]
print(graph(path))
```
%% Output
threshold found : 0.533203125
threshold found : 0.533203125
threshold found : 0.533203125
(4, 16)
0
pos depart : (31, 20) 0
(1, 1)
(1, 0)
(1, 1)
(1, 0)
(1, 1)
(1, 0)
(1, 0)
(1, 1)
(1, 0)
(1, 0)
(1, 1)
(1, 0)
blocked : [(43, 25)] point arrivee : 1
(4, 16)
-1
loooooop
pos depart : (4, 16) 0
(0, 1)
(0, 1)
(0, 1)
(0, 1)
(0, 1)
(0, 1)
(0, 1)
(0, 1)
(0, 1)
(0, 1)
(0, 1)
(0, 1)
(0, 1)
(1, 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
(-1, 0)
(-1, 1)
(-1, 0)
(-1, 0)
(-1, 0)
(-1, 0)
(-1, 0)
(-1, 0)
(-1, 0)
(-1, 1)
(-1, 0)
(-1, 0)
(-1, 0)
(-1, 0)
(-1, 1)
(-1, 0)
(-1, 0)
(-1, 0)
(-1, 1)
(-1, 1)
(-1, 0)
(-1, 1)
(-1, 0)
(-1, 1)
(-1, 1)
(0, 1)
(0, 1)
(-1, 1)
(-1, 1)
blocked : [(43, 25), (5, 15), (4, 17), (5, 15)] point arrivee : 0
[[(0, 1)], [(0, 0), (0, 0)]]
1
2
[[(0, 1)], [(2, 2), (2, 2)]]
%% Cell type:code id: tags:
``` python
path="/home/felix/Documents/work/FuzzyDoc/fuzzydoc/0Dot.jpg"
path="/home/felix/Documents/work/FuzzyDoc/fuzzydoc/imgs/new_database/Bounding_Box/Arial_600/num/8/591.jpg"
# path="/home/felix/Documents/work/FuzzyDoc/fuzzydoc/testCadre.png"
# path="/home/felix/Documents/work/FuzzyDoc/fuzzydoc/payslip_Arial_10_1_g.png"
# path="/home/felix/Documents/work/FuzzyDoc/fuzzydoc/imgs/new_database/documents/2PS_Arial_600.jpg"
# mask=detectTextAreas(path,'mask.png',square(25))
# im=load_image(path)
# for i in range(im.shape[0]):
# for j in range(im.shape[1]):
# if not(mask[i][j]):
# im[i][j]=255
# # plt.imshow(skeletonization_image(binarization_image(load_image(path),'otsu'),'lee'))
# newpath="imClean.png"
# plt.imsave(newpath,im)
debug=False ; veryDebug=False ; blocked=[]
print(graph(path))
```
%% Output
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/tmp/ipykernel_6160/2426019096.py in <module>
----> 1 im.index(255)
threshold found : 0.525390625
threshold found : 0.525390625
1
[[(1, 0), (0, 1), (1, 0), (0, 1)]]
AttributeError: 'numpy.ndarray' object has no attribute 'index'
%% Cell type:code id: tags:
``` python
```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment