-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmorph.py
More file actions
1386 lines (1234 loc) · 42 KB
/
morph.py
File metadata and controls
1386 lines (1234 loc) · 42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Copyright 2014 by Francisco de Assis Zampirolli from UFABC
License MIT
https://github.com/fzampirolli/morph
25 January 2024
"""
import matplotlib.pyplot as plt, numpy as np, cv2, requests, sys, subprocess
from PIL import Image
from skimage import io
class mm(object):
""" A helper class for image processing tasks. """
IN_COLAB = 'google.colab' in sys.modules #### INICIALIZATION ####
count_Images = 0
def __init__(self):
pass
@staticmethod
def install(packages=['matplotlib','numpy','opencv-python']):
"""This function will install the packages
input: <packages> list of packages.
Examples: mm.install(['matplotlib', 'scikit-image']) """
for package in packages:
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
#### IMAGE UTILITIES: CREATE, DRAW, CHECK ####
@staticmethod
def read(file):
""" Reads an image from a local file path or URL.
input: <str> File path or URL (full or 'id=keyGoogleDrive').
output: the read image.
Examples:
img_local = mm.read('image.png')
img_url = mm.read('https://example.com/image.jpg')
img_gdrive = mm.read('id=keyGoogleDrive')"""
if file.startswith(('http', 'id=')):
url, pre = '', 'https://drive.google.com/file/d/'
if pre in file:
url = 'https://drive.google.com/uc?export=view&id='
url += file[len(pre):].split('/')[0]
elif file.startswith('id='):
url = 'https://drive.google.com/uc?export=view&id=' + file[3:]
else:
url = file
return io.imread(url)
else:
return cv2.imread(file)
@staticmethod
def color(img):
""" Converts an image to RGB color space.
input: <numpy.ndarray> Image in BGR, grayscale, or RGBA format.
output: RGB image in <numpy.ndarray> format.
Example:
img = mm.read('image.png')
img_rgb = mm.color(img) """
if len(img.shape) == 2:
return cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
elif len(img.shape) == 3 and img.shape[2] == 4:
return cv2.cvtColor(img, cv2.COLOR_RGBA2RGB)
elif len(img.shape) == 3 and img.shape[2] == 3:
return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
else:
raise ValueError("Unsupported image format.")
@staticmethod
def gray(img):
""" Converts a color image to grayscale.
input: <numpy.ndarray> Input color image.
output: grayscale image.
Examples:
img = mm.read('image.png')
img_gray = mm.gray(img) """
if len(img.shape) == 3 and img.shape[2] == 4:
return cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY)
else:
return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
@staticmethod
def threshold(img, limiar=0):
""" Thresholds an input image by a threshold value or using Otsu's method.
input: <numpy.ndarray> Input image to be thresholded.
output: <numpy.ndarray> Thresholded image.
Examples:
img = mm.read('image.png')
th = mm.threshold(img) """
if limiar == 0:
value, th = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
else:
value, th = cv2.threshold(img, limiar, 255, cv2.THRESH_BINARY)
return th
@staticmethod
def show(*args):
""" This function will draw images f
input: <*args> set of images f_i, where i>0 is binary image
output: image drawing
Example:
f1, f2 = np.zeros((100, 100,3)), np.zeros((100, 100))
f2[50:60, 50:60] = 1
mm.show(f1, f2)"""
colors = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 0, 255], [0, 255, 255],
[255, 255, 0], [255, 50, 50], [50, 255, 50]] # red, green, blue, cyan, ...
f = args[0].copy()
for i in range(1,len(args)):
if i >= len(colors):
break
f[args[i] > 0] = colors[i-1]
_ = plt.imshow(f, "gray")
if not mm.IN_COLAB:
plt.savefig('fig_' + str(mm.count_Images).zfill(4) + '.png')
mm.count_Images += 1
@staticmethod
def readImg(h, w):
""" This function reads an image from input and returns it as a NumPy array.
input: size of image: height and width
output: image
Example:
mm.readImg(3, 4)
0 1 0 0
1 1 1 1
0 1 0 0
The function will return the following NumPy array:
array([[0, 1, 0, 0],
[1, 1, 1, 1],
[0, 1, 0, 0]]) """
m = np.zeros((h, w), dtype='uint8')
# Loop over each row of the image and read it from standard input.
for l in range(h):
# Split the row into individual pixel values and convert them to integers.
m[l] = [int(i) for i in input().split() if i]
return m
@staticmethod
def readImg2():
""" This function reads an image of varying size from standard input.
Example:
mm.readImg2()
255 0 255
128 64 192
0 192 128 """
b = []
read_row = input()
while read_row: # Read each line of the input until there is no more input.
# Split the line into individual pixel values and convert them to integers.
row = [int(i) for i in read_row.split() if i]
b.append(row) # Add the row to the list of rows.
read_row = input()
return np.array(b).astype('uint8')
@staticmethod
def randomImage(h, w, maxValue=9):
""" Creates a random image of size h x w with integer values in [0,maxValue].
input: size of image: height, width and max value
output: image
Example:
mm.randomImage(3, 3, maxValue=5)
The function will return a random NumPy array, such as:
array([[2, 1, 3],
[0, 4, 2],
[5, 1, 5]], dtype=uint8)"""
return np.random.randint(maxValue + 1, size=(h, w)).astype('uint8')
@staticmethod
def drawImage(f):
""" Converts the input image f into a string representation suitable for printing.
Args: f (ndarray): The input image.
Returns: A string representing the input image.
Example:
string_representation = mm.drawImage(f)
print(string_representation) """
l, c = f.shape
if np.min(f) < 0:
digits = '%' + str(1 + len(str(np.max(f)))) + 'd '
else:
digits = '%' + str(len(str(np.max(f)))) + 'd '
#print('"'+digits+'"')
string_representation = ''
for i in range(l):
for j in range(c):
string_representation += digits % f[i][j]
string_representation += '\n'
return string_representation
@staticmethod
def drawImagePlt(f):
""" Displays the input image f using Matplotlib.
Args: f (ndarray): The input image.
Example: drawImagePlt(f) """
h, w = f.shape
m = min(h, w)
# Set up the plot.
plt.figure(figsize=(m, m))
plt.rcParams['xtick.bottom'] = plt.rcParams['xtick.labelbottom'] = False
plt.rcParams['xtick.top'] = plt.rcParams['xtick.labeltop'] = True
# Display the image.
_ = plt.imshow(f, 'gray')
# Set the tick marks and labels.
plt.yticks(range(h))
plt.xticks(range(w))
plt.ylabel('y')
plt.xlabel('x')
# Add grid lines.
[plt.axvline(i + .5, 0, h, color='r') for i in range(w - 1)]
[plt.axhline(j + .5, 0, w, color='r') for j in range(h - 1)]
@staticmethod
def drawImageKernel(f,B,x,y):
"""This function will draw image f, considering a kernel
input:
- f: input image
- B: kernel
- x,y: center pixel of kernel
output:
- string: image drawing
"""
h,w = f.shape
Bh, Bw = B.shape
Bcx, Bcy = Bw//3, Bh//3
m = min(h,w)
plt.figure(figsize=(m,m))
plt.rcParams['xtick.bottom'] = plt.rcParams['xtick.labelbottom'] = False
plt.rcParams['xtick.top'] = plt.rcParams['xtick.labeltop'] = True
plt.imshow(f,'gray')
plt.yticks(range(h))
plt.xticks(range(w))
plt.ylabel('y')
plt.xlabel('x')
plt.title('Processando pixel (x,y)=(%d,%d)'%(x,y))
[plt.axvline(i+.5, 0, h, color='r') for i in range(w-1)]
[plt.axhline(j+.5, 0, w, color='r') for j in range(h-1)]
[plt.plot([i+x-Bcx-.5,i+x-Bcx-.5], [y-Bcy-.5,Bh+y-Bcy-.5], color='y', linewidth=5) for i in range(Bw+1)]
[plt.plot([x-Bcx-.5,x-Bcx+Bw-.5], [j+y-Bcy-.5, j+y-Bcy-.5], color='y', linewidth=5) for j in range(Bh+1)]
@staticmethod
def lblshow(f,border=3):
"""This function will draw image f with each component has a color
input:
- f: input image
- border: border optional [defaul=2]
output:
- y: color image
"""
from skimage import measure #<<<<<<<<<<<<<<<<<<
r = f
# Find contours at a constant value of 0.8
contours = measure.find_contours(r, 0.0)
fig, ax = plt.subplots()
ax.imshow(r, interpolation='nearest', cmap=plt.cm.gray)
for n, contour in enumerate(contours):
ax.plot(contour[:, 1], contour[:, 0], linewidth=border)
ax.axis('image')
ax.set_xticks([])
ax.set_yticks([])
_=plt.imshow(f,"gray")
if not mm.IN_COLAB:
plt.savefig('fig_'+str(mm.count_Images).zfill(4)+'.png')
mm.count_Images += 1
@staticmethod
def binary(f):
"""This function checks whether the image is binary
input:
- f: input image
output:
- y: True if binary image
"""
hist,bins = np.histogram(f.ravel(),256,[0,256])
if np.count_nonzero(hist > 0) == 2: # binary
return True
elif np.count_nonzero(hist > 0) > 2:
return False
else:
return None
##### OPERATIONS ON IMAGES (DO NOT USE NEIGHBORHOOD) #####
@staticmethod
def subm(f,g):
"""This fuction will be subtract f by g
input:
- f: input image
- g: input image
output:
- y: result of subtraction
"""
#return cv2.subtract(f,g)
return np.maximum(f-g,0)
@staticmethod
def addm(f,g):
"""This fuction will be add f by g
input:
- f: input image
- g: input image
output:
- y: result of add
"""
return cv2.add(f,g)
@staticmethod
def union(f,g):
"""This fuction will be union f by g
input:
- f: input image
- g: input image
output:
- y: result of add
"""
return np.maximum(f,g)
@staticmethod
def hist(img):
"""Função para retornar o histograma
Sintaxe:
hist = hist(img)
input: image
output hist
"""
H = np.zeros(np.max(img)+1, dtype=int)
for i in range(len(img.flatten())):
cor = img.flatten()[i]
H[cor] += 1
return np.asarray(H)
@staticmethod
def histPlus(img):
"""Função para retornar o histograma e todos os pixels de cada cor
Sintaxe:
hist, dict = histPlus(img)
input: image
output hist e dict
"""
H = np.zeros(np.max(img)+1, dtype=int)
vet = {} # cria um dicionário para os pixels de cada cor
for i in range(len(img.flatten())):
cor = img.flatten()[i]
H[cor] += 1
if str(cor) in vet.keys():
vet[str(cor)].append(i)
else:
vet[str(cor)] = [i]
return H,vet
@staticmethod
def equalizacao(image):
"""Função para retornar a imagem equalizada pelo valor máximo
Sintaxe:
imgEqu = equalizacao(image)
input: image
output imgEqu
"""
@staticmethod
def somaAcumulada(prob):
soma = np.zeros(len(prob))
soma[0] = prob[0]
for i in range(1,len(prob)):
soma[i] = soma[i-1]+prob[i]
return np.asarray(soma)
hist = mm.hist(image) # histograma
prob = hist/sum(hist) # probabilidades
soma = somaAcumulada(prob) # função de distribuição acumulada
soma = soma*(np.max(image))# multiplicando pelo valor máximo da img
soma = np.round(soma) # arredondando para obter os níveis de cinza correspondetes
l,c = image.shape
imgEqua = np.zeros([l,c])
for i in range(l):
for j in range(c):
imgEqua[i,j] = soma[image[i,j]]
return imgEqua.astype('int')
#### MINKOWSKI SUM ####
@staticmethod
def sesum(b,n=0):
"""This function will be create a structure function nB by Minkowski sum B
input:
- b: structure fuction
- n: number of sum
output:
- y: result of Minkowski sum
"""
def _sesum(nb,b):
h,w = b.shape
nbh,nbw = nb.shape
H = nbh+h-1 if h%2 else nbh+h
W = nbw+w-1 if w%2 else nbw+w
Hc,Wc = H//3, W//3
r = np.zeros((H,W)).astype('uint8')
r[h//3:-(h//3),w//3:-(w//3)] = nb
return cv2.dilate(r,b).astype('uint8')
B = b.copy()
for i in range(n):
B = _sesum(B,b)
return B
@staticmethod
def sebox(n=0):
"""This function will be create a box structure function nB by Minkowski sum B
input:
- n: number of sum
output:
- y: result of Minkowski sum
"""
B = np.ones((3, 3), dtype='uint8')
return mm.sesum(B,n)
@staticmethod
def secross(n=0):
"""This function will be create a cross structure function nB by Minkowski sum B
input:
- n: number of sum
output:
- y: result of Minkowski sum
"""
B = np.ones((3, 3), dtype='uint8')
B[0,0] = B[0,2] = B[2,0] = B[2,2] = 0
return mm.sesum(B,n)
@staticmethod
def sedisk(n=3):
"""This function will be create a disk structure function
input:
- n: number of sum
output:
- y: result of disk
"""
return cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(n,n))
#### BASIC MORPHOLOGICAL OPERATORS ####
@staticmethod
def ero(f,Bc=np.zeros((3,3),dtype= 'uint8')):
"""This function will create an erosion of f by Bc
input:
- f: input image
- Bc: structuring element
output:
- y: result of filter
"""
try:
return cv2.erode(f,Bc)
except: # with weight in Bc
return mm.ero1(f,Bc)
@staticmethod
def dil(f,Bc=np.zeros((3,3),dtype= 'uint8')):
"""This function will create an dilate of f by Bc
input:
- f: input image
- Bc: structuring element
output:
- y: result of filter
"""
try:
return cv2.dilate(f,Bc)
except: # with weight in Bc
return mm.dil1(f,Bc)
@staticmethod
def ero0(f,Bc=np.zeros((3,3),dtype= 'uint8')):
"""This function will create an erosion of f by Bc
input:
- f: input image
- Bc: structuring element
output:
- y: result of filter
"""
H,W = f.shape
Bh, Bw = Bc.shape
g = f.copy() # nas listas, as vezes eu uso assim
# para varrer imagem na ordem raster
for y in range(H): # para cada linha y
for x in range(W): # para cada coluna x
# para cada vizinho de (x,y)
for by in range(Bh):
for bx in range(Bw):
viz_y = int(y + by - Bh/2 + 0.5)
viz_x = int(x + bx - Bw/2 + 0.5)
# verificar o domínion da image
if Bc[by,bx] and 0 <= viz_y < H and 0 <= viz_x < W:
# para calcular o mínino dos vizinhos
if g[y,x] > f[viz_y,viz_x]:
g[y,x] = f[viz_y,viz_x]
return g
@staticmethod
def dil0(f,Bc=np.zeros((3,3),dtype= 'uint8')):
"""This function will create a dilate of f by Bc
input:
- f: input image
- Bc: structuring element
output:
- y: result of filter
"""
H,W = f.shape
Bh, Bw = Bc.shape
Bcy, Bcx = Bh/2, Bw/2
g = f.copy() # nas listas, as vezes eu uso assim
# para varrer imagem na ordem raster
for y in range(H): # para cada linha y
for x in range(W): # para cada coluna x
# para cada vizinho de (x,y)
for by in range(Bh):
for bx in range(Bw):
viz_x = int(x + bx - Bcx + 0.5)
viz_y = int(y + by - Bcy + 0.5)
# verificar o domínion da image
if Bc[by,bx] and 0 <= viz_x < W and 0 <= viz_y < H:
# para calcular o máximo dos vizinhos
if g[y,x] < f[viz_y,viz_x]:
g[y,x] = f[viz_y,viz_x]
return g
@staticmethod
def ero1(f,b=np.zeros((3,3),dtype= 'uint8')):
"""This function will create an erosion of f by b
input:
- f: input image
- b: structuring element
output:
- y: result of filter
"""
H,W = f.shape
Bh, Bw = b.shape
g = f.copy() # nas listas, as vezes eu uso assim
# para varrer imagem na ordem raster
for y in range(H): # para cada linha y
for x in range(W): # para cada coluna x
# para cada vizinho de (x,y)
for by in range(Bh):
for bx in range(Bw):
viz_y = int(y + by - Bh/2 + 0.5)
viz_x = int(x + bx - Bw/2 + 0.5)
# verificar o domínion da image
if 0 <= viz_y < H and 0 <= viz_x < W:
# para calcular o mínino dos vizinhos
if g[y,x] > f[viz_y,viz_x] - b[by,bx]:
g[y,x] = f[viz_y,viz_x] - b[by,bx]
return g
@staticmethod
def dil1(f,b=np.zeros((3,3),dtype= 'uint8')):
"""This function will create a dilate of f by b
input:
- f: input image
- b: structuring element
output:
- y: result of filter
"""
H,W = f.shape
Bh, Bw = b.shape
g = f.copy() # nas listas, as vezes eu uso assim
# para varrer imagem na ordem raster
for y in range(H): # para cada linha y
for x in range(W): # para cada coluna x
# para cada vizinho de (x,y)
for by in range(Bh):
for bx in range(Bw):
viz_y = int(y + by - Bh/2 + 0.5)
viz_x = int(x + bx - Bw/2 + 0.5)
# verificar o domínion da image
if 0 <= viz_y < H and 0 <= viz_x < W:
# para calcular o mínino dos vizinhos
if g[y,x] < f[viz_y,viz_x] + b[by,bx]:
g[y,x] = f[viz_y,viz_x] + b[by,bx]
return g
@staticmethod
def correlacao0(F, kernel, bias):
"""This function will create an correlation of f by b
input:
- f: input image
- b: kernel
output:
- y: result of filter
"""
Bh, Bw = kernel.shape
if (Bh == Bw): # apenas para kernel quadrado
H, W = f.shape
H = H - Bh + 1 # REMOVO A BORDA!!!
W = W - Bw + 1 # REMOVO A BORDA!!!
new_f = np.zeros((H,W))
for i in range(H): # para cada linha i
for j in range(W): # para cada coluna j
new_f[i][j] = np.sum(f[i:i+Bh, j:j+Bw]*kernel) + bias
return new_f.astype(np.uint8)
##### MORPHOLOGICAL OPERATORS USING DILATATION OR EROSION #####
@staticmethod
def gradm(f,b=np.zeros((3,3),dtype= 'uint8')):
"""This fuction will be dilate f by b minus erodel f by b
input:
- f: input image
- b: neighbors
output:
- y: result of condictional dilations
"""
return mm.subm(mm.dil(f,b),mm.ero(f,b))
@staticmethod
def cero(f,g,b=np.zeros((3,3),dtype= 'uint8'),n=1):
"""This fuction will be erode g with maximum f, n times
input:
- f: input image
- g: mark image
- b: neighbors
- n: number of iterations
output:
- y: result of condictional erodes
"""
y = np.maximum(f,g)
for i in range(n):
d = cv2.erode(y,b)
y = np.maximum(d,g)
return y
@staticmethod
def cdil(f,g,b=np.zeros((3,3),dtype= 'uint8'),n=1):
"""This fuction will be dilate g with minimum f, n times
input:
- f: input image
- g: mark image
- b: neighbors
- n: number of iterations
output:
- y: result of condictional dilations
"""
y = np.minimum(f,g)
for i in range(n):
d = cv2.dilate(y,b)
y = np.minimum(d,g)
return y
@staticmethod
def infrec(f,g,b=np.zeros((3,3),dtype= 'uint8')):
"""This function will be dilate g with minimum f, until converge
input:
- f: input image
- g: mark image
- b: neighbors
output:
- y: result of inf-reconstruction
"""
y = np.minimum(f,g)
y1 = np.zeros_like(f)
while not np.array_equal(y,y1):
y1 = y
d = cv2.dilate(y,b)
y = np.minimum(d,g)
return y
@staticmethod
def suprec(f,g,b=np.zeros((3,3),dtype= 'uint8')):
"""This function will be erode g with maximum f, until converge
input:
- f: input image
- g: mark image
- b: neighbors
output:
- y: result of sup-reconstruction
"""
y = np.maximum(f,g)
y1 = np.ones_like(f)*255
while not np.array_equal(y,y1):
y1 = y
d = cv2.erode(y,b)
y = np.maximum(d,g)
return y
@staticmethod
def closerec(f,b=np.zeros((3,3),dtype= 'uint8'),bc=np.zeros((3,3),dtype= 'uint8')):
"""This function will be erode g with maximum f, until converge
input:
- f: input image
- b: mark image
- bc: neighbors
output:
- y: result of sup-reconstruction
"""
return mm.suprec(f, mm.dil(f,b), bc)
@staticmethod
def areaopen(f,a):
"""This function will be dilate g with minimum f, until converge
input:
- f: input image
- a: area
#- Bc: neighbors
output:
- y: result of areaopen
"""
def _areaopen(f,a):
y = np.zeros(f.shape).astype(int)
if mm.binary(f): # binary
num_labels, labels_im = cv2.connectedComponents(f)
for i in range(1,num_labels):
area = np.sum(labels_im[labels_im==i] > 0)
if area > a: # filtra por área aproximada
#print('area:',area)
y[labels_im==i] = area
else: # gray scale
hist,bins = np.histogram(f.ravel(),256,[0,256])
for cor,h in enumerate(hist):
if h and cor:
#print('>>cor:',cor)
ret, fcor = cv2.threshold(f, cor, 255, cv2.THRESH_BINARY)
fo = _areaopen(fcor,a)
if np.amax(fo) == 0:
break
y += fo
return y
return _areaopen(f,a)
@staticmethod
def asf(f,filter='OC',b=np.zeros((3,3),dtype= 'uint8'),n=1):
"""This function will create an alternating sequential filter
input:
- f: input image
- b: structuring fuctions
- n: number of iterations
- filter: 'OC', 'CO', 'OCO', 'COC' [Default: 'OC']
output:
- y: result of filter
ATENÇÃO:
"""
filter = filter.upper()
y = f.copy()
if filter=='OC':
for i in range(n):
bi = mm.sesum(b,i)
y = cv2.morphologyEx(y, cv2.MORPH_OPEN, bi)
y = cv2.morphologyEx(y, cv2.MORPH_CLOSE, bi)
elif filter=='CO':
for i in range(n):
bi = mm.sesum(b,i)
y = cv2.morphologyEx(y, cv2.MORPH_CLOSE, bi)
y = cv2.morphologyEx(y, cv2.MORPH_OPEN, bi)
elif filter=='OCO':
for i in range(n):
bi = mm.sesum(b,i)
y = cv2.morphologyEx(y, cv2.MORPH_OPEN, bi)
y = cv2.morphologyEx(y, cv2.MORPH_CLOSE, bi)
y = cv2.morphologyEx(y, cv2.MORPH_OPEN, bi)
elif filter=='COC':
for i in range(n):
bi = mm.sesum(b,i)
y = cv2.morphologyEx(y, cv2.MORPH_CLOSE, bi)
y = cv2.morphologyEx(y, cv2.MORPH_OPEN, bi)
y = cv2.morphologyEx(y, cv2.MORPH_CLOSE, bi)
return y
@staticmethod
def openth(f,b=np.zeros((3,3),dtype= 'uint8')):
return mm.subm(f,cv2.morphologyEx(f, cv2.MORPH_OPEN, b))
@staticmethod
def openth1(f,b=np.zeros((3,3),dtype= 'uint8')):
return mm.subm(f, mm.dil1(mm.ero1(f,b),b) )
@staticmethod
def closeth(f,b=np.zeros((3,3),dtype= 'uint8')):
return mm.subm(cv2.morphologyEx(f, cv2.MORPH_CLOSE, b),f)
@staticmethod
def closerecth(f,b=np.zeros((3,3),dtype= 'uint8')):
return mm.subm(cv2.morphologyEx(f, cv2.MORPH_CLOSE, b),f)
@staticmethod
def open(f,b=np.zeros((3,3),dtype= 'uint8')):
return cv2.morphologyEx(f, cv2.MORPH_OPEN, b)
@staticmethod
def close(f,b=np.zeros((3,3),dtype= 'uint8')):
return cv2.morphologyEx(f, cv2.MORPH_CLOSE, b)
@staticmethod
def water0(f,b=np.zeros((3,3),dtype= 'uint8'), op='region'):
"""This function will create the watershed
input:
- f: input binary image
- op: regions of watershed
output:
- y: watershed
"""
f = mm.label0(f,b)
h,w = f.shape
bh, bw = b.shape
g = f.copy()
while np.amin(g)==0:
for x in range(h):
for y in range(w):
for bx in range(bh):
for by in range(bw):
viz_x = int(x + bx - bh/2 + 0.5)
viz_y = int(y + by - bw/2 + 0.5)
if 0 <= viz_x < h and 0 <= viz_y < w:
if g[x,y] == 0 and g[x,y] < f[viz_x,viz_y]:
g[x,y] = f[viz_x,viz_y]
f = g.copy()
if op == 'region':
return g
elif op == 'line':
return mm.gradm(g,mm.secross())
@staticmethod
def waterB(f,m,b=np.zeros((3,3),dtype= 'uint8'), op='region'):
"""This function will create the watershed, process only border pixel of each object
input:
- f: input binary image
- op: regions of watershed
output:
- y: watershed
"""
m = mm.label0(m,b)
h,w = m.shape
bh, bw = b.shape
queue = []
for x in range(h):
for y in range(w):
if m[x,y]:
for bx in range(bh):
for by in range(bw):
viz_x = int(x + bx - bh/2 + 0.5)
viz_y = int(y + by - bw/2 + 0.5)
if 0 <= viz_x < h and 0 <= viz_y < w:
if not m[viz_x,viz_y]:
queue.append([abs(f[x,y]-f[viz_x,viz_y]), x, y])
while len(queue):
#queue = sorted(queue, key=lambda a:a[0])
cor_diff,x,y = queue.pop(0)
cor = m[x,y]
for bx in range(bh):
for by in range(bw):
viz_x = int(x + bx - bh/2 + 0.5)
viz_y = int(y + by - bw/2 + 0.5)
if 0 <= viz_x < h and 0 <= viz_y < w:
if not m[viz_x,viz_y]:
m[viz_x,viz_y] = cor
queue.append([abs(f[x,y]-f[viz_x,viz_y]), viz_x, viz_y])
if op == 'region':
return m
elif op == 'line':
return mm.gradm(m,mm.secross())
@staticmethod
def watershed(f,mark,op='region'):
"""This function will create the watershed
input:
- f: input image
- f==[] # binary watershed by skimage
- else # condictional watershed by cv2
- mark: markers image
- op: region or line [default: region]
output:
- y: watershed
"""
mark = mark*255 if np.amax(mark)==1 else mark
if len(f): # condictional watershed by cv2
ret, markers = cv2.connectedComponents(mark)
w = cv2.watershed(f,markers)
if op=='line':
f[markers == -1] = [255,0,0]
return f
else:
return w
else: # binary watershed by skimage
from scipy import ndimage as ndi
from skimage.segmentation import watershed
fones = np.ones_like(mark)*255
markers = ndi.label(mark)[0]
w = watershed(fones, markers, mask=fones)
if op=='line':
return np.array((w-cv2.erode(w.astype('uint16'),mm.sebox()))>0).astype('uint16')
else:
return w
@staticmethod
def regmax(f,b=np.ones((3,3),dtype='uint8')):
"""This function will be calculate region maximum
input:
- f: input image
- b: neighbors
output:
- y: result of regmax
"""
if np.amax(f)<=255:
k = 255
else:
k = 65535
fminus = mm.subm(f,1)
g = mm.subm(f,mm.infrec(fminus,f,b))
return mm.union(mm.threshold(g,0),mm.threshold(f,k))
@staticmethod
def regmin(f,b=np.ones((3,3),dtype='uint8')):
"""This function will be calculate region minimum
input:
- f: input image
- b: neighbors
output:
- y: result of regmax
"""
fplus = mm.addm(f,1);
g = mm.subm(mm.suprec(fplus,f,b),f);
return mm.union(mm.threshold(g,1),mm.threshold(f,0))
def blob(f,op='area',border=1,precision=0.01,show='True'):
"""This function will be calculate topology of each connect component
input:
- f: input image
- op: 'area', 'perimeter', etc [default='area']
- border: border of lines [default=1]
- precision: precision of polygonon [default=0.01]
- show=True, return image, else, return measure
output:
- y: image with op or measure
"""
if mm.binary(f): # binary
measures = []
cont, _ = cv2.findContours(f.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
color_img = cv2.cvtColor(f, cv2.COLOR_GRAY2RGB)
if op=='area':
color_img = np.zeros_like(f).astype('uint32')
num_labels, labels_im = cv2.connectedComponents(f)
for i in range(1,num_labels):
area = np.sum(labels_im[labels_im==i] > 0)
measures.append(area)
color_img[labels_im==i] = area
elif op=='textLabel':
for k,c in enumerate(cont):
x,y,w,h = cv2.boundingRect(c)
measures.append(k+1)
cv2.putText(color_img, str(k+1),(x+w//3, y+h//3), cv2.FONT_HERSHEY_SIMPLEX, 0.2,(255,0,0),border,cv2.LINE_AA)
elif op=='textPer':
cont, _ = cv2.findContours(f.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
color_img = cv2.cvtColor(f, cv2.COLOR_GRAY2RGB)
for k,c in enumerate(cont):
perimeter = int(cv2.arcLength(c,True))
measures.append(perimeter)
x,y,w,h = cv2.boundingRect(c)
cv2.putText(color_img, str(perimeter),(x+w//3, y+h//3), cv2.FONT_HERSHEY_SIMPLEX, 0.2,(255,0,0),border,cv2.LINE_AA)
elif op=='textArea':
cont, _ = cv2.findContours(f.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
color_img = cv2.cvtColor(f, cv2.COLOR_GRAY2RGB)
for k,c in enumerate(cont):
area = int(cv2.contourArea(c))
measures.append(area)
x,y,w,h = cv2.boundingRect(c)
cv2.putText(color_img, str(area),(x+w//3, y+h//3), cv2.FONT_HERSHEY_SIMPLEX, 0.2,(255,0,0),border,cv2.LINE_AA)