-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFilters.py
1172 lines (936 loc) · 38 KB
/
Filters.py
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
import sys
import os
import os.path
import cv2
import numpy as np
import matplotlib.pyplot as plt
import imagecontainer as ic
import choices as clt
from PIL import Image
from skimage import img_as_float
from skimage import io, color, morphology, exposure
from skimage.morphology import skeletonize, thin, erosion, dilation, opening, \
closing, white_tophat, black_tophat, skeletonize, convex_hull_image
import ImageFilters as IF
from ImageFilters import Sequence
from skimage.restoration import denoise_nl_means, estimate_sigma
from mpl_toolkits import mplot3d
file_path = "" # String with image path
img = cv2.imread("") # Image variable
# Elements for load, undo and redo options
img_list = [] # Image collection
actual_loaded = 0 # Index of actual processing image
# Variables for hsv processing menu
channel_to_save = False # Used in hsv_processing_menu
selected_channel = cv2.imread("") # Actual loaded channel
# Image container
imageContainer = ic.ImageContainer()
# list of functions used by user
choices = clt.Choices()
#new_path = r'C:\Users\Mario\Desktop\image_20.jpg'
# Main Menu
def main_menu():
global file_path
global test
# choices.add_choice(perspective_correction.__name__)
# for function in choices.get_list():
# globals()[function]
# Image container test
# Load all images from selected path
if imageContainer.number_of_elements == 0:
imageContainer.load(r'E:\Data\Dokumenty\Studia\Praca\MGR\Serie\Test4', r'.jpg')### loading off
print(imageContainer.number_of_elements)
imageContainer.save()
# test = IF.Sequence()
else:
print("Images already loaded to the list...")
print(imageContainer.number_of_elements)
# imageContainer.save()
while True:
print("************Menu************")
# No path info and manu content set
if file_path == "":
print("***No file path defined!***")
# Menu content set
content = """1 - Chose image path
x - Exit:"""
else:
content = """1 - Chose image path
2 - Show an image
3 - Image processing
4 - Load NPY
x - Exit:"""
# Main options
# Red user's chose
choice = input(content)
if choice == "1":
chose_path()
elif choice == "2" and file_path != "":
show_img(0)
elif choice == "3" and img.size != 0:
processing_menu()
elif choice == "4":
load_npy()
elif choice == "x" or choice == "X":
menu_exit()
else:
print("Wrong input")
main_menu()
# Processing Menu
def processing_menu():
while True:
print("************Processing Menu************")
content = """1 - Show original image
2 - Filter fast denoising
3 - Change to HSV
4 - Normalise
5 - Histogram
6 - Undistortion
7 - Blur
8 - Skimage nl fast denoise
9 - Gamma corectiono test
B - Between values filter
L - Binearisation
P - Perspective correction
M - Morphological operation
O - Gausian otsus filtering
G - 2 gray
w - Save picture
R - Run sequence
V - Visualisation
s - Show
u - Undo
r - Redo
x - Back to Main Menu:"""
# Main options
# Red user's chose
choice = input(content)
if choice == "1":
show_img(0) # Show original image
elif choice == "2" and file_path != "":
filter_denoising()
elif choice == "3" and img.size != 0:
rgb_to_hsv()
elif choice == "4" and img.size != 0:
normalise_img()
elif choice == "5" and img.size != 0:
show_histogram()
elif choice == "6" and img.size != 0:
filter_undistort()
elif choice == "7" and img.size != 0:
gausianblur()
elif choice == "8" and img.size != 0:
skinldenoise()
elif choice == "9" and img.size != 0:
gammacorection()
elif choice == "B" or choice == "b":
rgb_range_filter()
elif choice == "M" or choice == "m":
morphology_filter()
elif choice == "G" or choice == "g":
togray()
elif choice == "O" or choice == "o":
gausianotsus()
elif choice == "P" or choice == "p":
perspective_correction()
elif choice == "L" or choice == "l":
binearization()
elif choice == "W" or choice == "w":
save_picture()
elif choice == "R" or choice == "r":
imageContainer.dosequence(['barell', 'rgbrange', 'morph', 'perspective', 'thinning', 'binearization'])
# trzeba najpierd odfitrować morph, później korekcja perspektywy i dopieto thinning bo powstają rozlania
#try to save image matrix
imageContainer.save_matrix()
elif choice == "V" or choice =="v":
visualisation()
elif choice == "u" or choice == "U": # Undo last filter
undo_edit()
elif choice == "r" or choice == "R": # Redo last filter
redo_edit()
elif choice == "s" or choice == "S": # Show actual loaded image
show_img(actual_loaded)
elif choice == "x" or choice == "X":
main_menu()
else:
print("Wrong input")
processing_menu()
def hsv_processing_menu():
while True:
global selected_channel
global channel_to_save # Gets true if you chose specific channel
# Aditional information when specyfic chanel is selected
if channel_to_save:
aditional = "\nF - Standard deviation channel filtering" \
"\nB - Filter between specific values"
else:
aditional = ""
print("************HSV Processing************")
content = """SH - Show H channel
SS - Show S channel
SV - Show V channel%s
S - Save selected channel
x - Cancel:""" % aditional
# Main options
# Read user's chose
choice = input(content)
if choice == "SH" or choice == "sh":
selected_channel = img_list[actual_loaded][:, :, 0] # Load H from HSV
channel_to_save = True
show_one_img(selected_channel)
elif choice == "SS" or choice == "ss":
selected_channel = img_list[actual_loaded][:, :, 1] # Load S from HSV
channel_to_save = True
show_one_img(selected_channel)
elif choice == "SV" or choice == "sv":
selected_channel = img_list[actual_loaded][:, :, 2] # Load V from HSV
channel_to_save = True
show_one_img(selected_channel)
elif choice == "F" or choice == "f":
factor = input("Insert the factor:")
sf_filter(selected_channel, factor)
channel_to_save = True
elif choice == "B" or choice == "b":
min_value = input("Insert the value (min) ")
max_value = input("Insert the value (max) ")
hsv_range_filter(selected_channel, min_value, max_value)
channel_to_save = True
elif choice == "s" or choice == "S":
if channel_to_save:
add_to_stack(selected_channel)
channel_to_save = False # Default value
selected_channel = cv2.imread("") # Delete image from variable
processing_menu()
else:
print("No specyfic channel selected-full HSV already saved")
elif choice == "x" or choice == "X":
channel_to_save = False # Default value
selected_channel = cv2.imread("") # Delete image from variable
processing_menu()
else:
print("Wrong input")
hsv_processing_menu()
# Perspective correction
def perspective_correction():
img_perspective = load_a_picture()
# print(len(img_perspective.shape))
# tu jest problem z rozpakowaniem gdy mamy obraz rgb lub grayscale trzeba wykrywac czy jest i rozpakować do 2 lub 3 zmiennych
if len(img_perspective.shape) == 3:
rows, cols, ch = img_perspective.shape
else:
rows, cols = img_perspective.shape
# Transformation matrix from getPerspectiveTransform
M = [[ 4.61386962e-01, -5.65776917e-01, 3.24411613e+02],
[ 7.19903651e-04, 3.07245847e-01, 8.75850391e+01],
[ 1.25418754e-06, -9.41057451e-04, 1.00000000e+00]]
undistorted = cv2.warpPerspective(np.float32(img_perspective), np.float32(M), (np.float32(cols), np.float32(rows)))
undistorted = undistorted.astype(np.uint8) ## protect data cliping
add_to_stack(undistorted)
show_img(actual_loaded)
processing_menu()
# Close the program
def menu_exit():
# Proof question EXIT
print("Do you really want to exit? Y/N")
final_chose = input()
print(final_chose)
if final_chose == "Y" or final_chose == "y":
sys.exit()
else:
main_menu()
# Load NPY as image matrix
def load_npy():
imageContainer.load_matrix()
# Chose path for image
def chose_path():
global file_path # String with image path
global img # Image variable
# Elements for load, undo and redo options
global img_list # Image collection
global actual_loaded # Index of actual processing image
# Reset variables
file_path = ""
img = cv2.imread("")
img_list = []
actual_loaded = 0
global new_path
new_path = r'E:\Data\Dokumenty\Studia\Praca\MGR\Serie\CamCal\shuttertest\image-test3.jpg' # C:\Users\Mario\Desktop\test1\image_26.jpg C:\Users\Mario\Desktop\PerspectiveTest\image1.jpg' # fixed path for testing
# input("""**Chose the path**
# Press c to cancel
# Please insert the path:""")
if new_path == "c" or new_path == "C":
main_menu()
else:
if os.path.isfile(new_path):
if new_path.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
file_path = new_path
load_image()
else:
file_path = ""
print("Wrong extension! Use: png, jpg or bmp.")
chose_path()
else:
file_path = ""
print("The file path does not exist!")
# Load image from the path
def load_image():
global img
img = cv2.imread(file_path)
img_list.append(img)
# Binarisation
def binearization():
img_binarization = load_a_picture()
# gray = cv2.cvtColor(img_binarization, cv2.COLOR_BGR2GRAY)
# bin = np.nonzero(gray)
# plt.plot(bin[1], bin[0], '.')
# plt.plot(red_range = np.logical_and(bin[1] <= 537, arr[:, :, 0] <= rgb_range[0][1]))
# print(bin[1])
# print(bin[0])
# plt.show()
# processing_menu()
if len(img_binarization.shape) >= 3:
try:
print("***converting to grayscale***")
gray = cv2.cvtColor(np.float32(img_binarization), cv2.COLOR_BGR2GRAY)
bin = np.nonzero(gray)
imageContainer.add_matrix([bin[1] / 60.884, bin[0] / 31.597]) # add matrix to image container
plt.plot(bin[1] / 60.884, bin[0] / 31.597, '.') # convertion to cm y/34.909090 x/58.272727
##test
print(imageContainer.image_matrix)
print(imageContainer.image_matrix[0][1])
plt.plot(imageContainer.image_matrix[0][1], imageContainer.image_matrix[0][2], '.')
plt.show()
processing_menu()
except ValueError:
print(ValueError)
print("Can't convert this image to grayscale")
input("press any key to back to processing menu...")
processing_menu()
else:
try:
print("***Collecting data..***")
bin = np.nonzero(img_binarization)
imageContainer.add_matrix([bin[1] / 60.884, bin[0] / 31.597]) # add matrix to image container
plt.plot(bin[1] / 60.884, bin[0] / 31.597, '.') # convertion to cm y/34.909090 x/58.272727
plt.axis('square')
plt.show()
processing_menu()
except ValueError:
print(ValueError)
print("Can't plot this image...")
input("press any key to back to processing menu...")
processing_menu()
# gamma corection
def gammacorection():
image = load_a_picture()
# ima = exposure.adjust_gamma(image, 2)
ima = exposure.adjust_sigmoid(image, 0.8)
add_to_stack(ima)
show_img(actual_loaded)
processing_menu()
# finding range for rgb range filter
def findrgbrange(image):
from kneed import KneeLocator
RGB = []
# Computing the knees for rgb
if len(image.shape) >= 3:
try:
print("***Colour RGB range detection***")
for i in range(0, 3):
cdf3 = exposure.cumulative_distribution(image[:, :, i])
# print(i)
# print(image.shape)
# print(image[:, :, i].shape)
# print(cdf3)
# div = np.gradient(np.array([cdf3[0], cdf3[1]], dtype=float))
# print(div)
# plt.plot(div[0], div[1])
# plt.plot(cdf3[1], cdf3[0])
kneedle = KneeLocator(cdf3[1], cdf3[0], curve='convex', direction='increasing')
# kneedle.plot_knee()
# finding the knee
# kneedle = KneeLocator(-div[0][0], div[1][1], S=5, curve='convex', direction='increasing')
# kneedle.plot_knee()
print(round(kneedle.knee, 3))
RGB.append(int(kneedle.knee))
print(round(kneedle.knee_y, 3))
# plt.show()
return RGB
except ValueError:
print(ValueError)
print("Can't get the range")
input("press any key to back to processing menu...")
return False
else:
try:
print("***Grayscale range detection***")
cdf3 = exposure.cumulative_distribution(image)
# print(image.shape)
# print(cdf3)
kneedle = KneeLocator(cdf3[1], cdf3[0], curve='convex', direction='increasing')
# kneedle.plot_knee()
print(round(kneedle.knee, 3))
RGB.append(int(kneedle.knee))
print(round(kneedle.knee_y, 3))
return RGB
except ValueError:
print(ValueError)
print("Can't get the range")
input("press any key to back to processing menu...")
return False
# Show the image from img_list
def show_img(image_number):
print(image_number)
img_to_show = img_list[image_number]
print(type(img_to_show))
# img_to_show = cv2.cvtColor(img_list[int(image_number)], cv2.COLOR_BGR2RGB)
plt.imshow(img_to_show)
plt.show()
# plt.imshow(img_list[image_number])
# plt.show()
# cv2.namedWindow('image', cv2.WINDOW_KEEPRATIO)
# cv2.imshow('image', img_list[image_number])
# cv2.waitKey(0)
# cv2.destroyAllWindows()
# Show single image
def show_one_img(image):
# img_to_show = cv2.cvtColor(cv2.UMat(image), cv2.COLOR_BGR2RGB)
plt.imshow(image)
plt.show()
# cv2.namedWindow('image', cv2.WINDOW_NORMAL)
# cv2.imshow('image', image)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
# Processing menu
def image_processing():
clear()
# Clear the view
def clear():
os.system('cls')
# Load picture function from saved list
def load_a_picture():
global actual_loaded
loaded_image = img_list[actual_loaded]
return loaded_image
# Filter with fast denoising
def filter_denoising():
img_filter_b = load_a_picture()
if len(img_filter_b.shape) >= 3:
try:
import time
start = time.time()
print("***Colour denoising***")
img_filter_b = img_list[actual_loaded]
img_filter_b = cv2.fastNlMeansDenoisingColored(img_filter_b, None, 20, 20, 7, 15) # Denoising colour image
end = time.time()
print(end - start)
add_to_stack(img_filter_b)
show_img(actual_loaded)
except ValueError:
print(ValueError)
print("Can't denoise this image-try undo")
input("press any key to back to processing menu...")
processing_menu()
else:
try:
print("***Grayscale denoising***")
img_filter_b = cv2.cv2.fastNlMeansDenoising(img_filter_b) # Denoising grayscale image
add_to_stack(img_filter_b)
show_img(actual_loaded)
except ValueError:
print(ValueError)
print("Can't denoise this image-try undo")
input("press any key to back to processing menu...")
processing_menu()
# Geometrical undistorion
def filter_undistort():
img_distortion = load_a_picture()
# src = img_undistortion
mtx = ([1.43007971e+03, 0.00000000e+00, 6.23310543e+02],
[0.00000000e+00, 1.41523006e+03, 3.20646989e+02],
[0.00000000e+00, 0.00000000e+00, 1.00000000e+00])
dist = ([-4.17384627e-01, 1.50022972e-01, -3.18096773e-04, 9.81290115e-04,
1.45909991e-01])
# w = src.shape[1]
# h = src.shape[0]
newcameramtx = ([1.24925537e+03, 0.00000000e+00, 6.21223086e+02],
[0.00000000e+00, 1.23910193e+03, 3.17573223e+02],
[0.00000000e+00, 0.00000000e+00, 1.00000000e+00])
# undistortion
dst = cv2.undistort(np.float32(img_distortion), np.float32(mtx), np.float32(dist), None, np.float32(newcameramtx))
dst = dst.astype(np.uint8) ## protect data cliping
add_to_stack(dst)
show_img(actual_loaded)
processing_menu()
# gausian blur
def gausianblur():
blur = load_a_picture()
blur = cv2.bilateralFilter(blur, 10, 50, 50)
add_to_stack(blur.astype(np.uint8))
show_img(actual_loaded)
processing_menu()
# to gray
def togray():
color = load_a_picture()
gray = cv2.cvtColor(color, cv2.COLOR_BGR2GRAY)
add_to_stack(gray)
show_img(actual_loaded)
processing_menu()
def skinldenoise():
noisy = load_a_picture()
patch_kw = dict(patch_size=5, # 5x5 patches
patch_distance=6, # 13x13 search area
multichannel=True)
sigma_est = np.mean(estimate_sigma(noisy, multichannel=True))
denoise2_fast = denoise_nl_means(noisy, h=0.6 * sigma_est, sigma=sigma_est,
fast_mode=True, **patch_kw)
add_to_stack(denoise2_fast)
show_img(actual_loaded)
processing_menu()
# gausian otsu filtering
def gausianotsus():
src = load_a_picture()
otsus_img = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(otsus_img, (5, 5), 0)
ret3, th3 = cv2.threshold(blur, 150, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
add_to_stack(th3)
show_img(actual_loaded)
processing_menu()
# def hessian():
# from skimage.feature import hessian_matrix, hessian_matrix_eigvals
# morph_img = load_a_picture()
# assume you have an image img
# hxx, hxy, hyy = hessian_matrix(img, sigma=3)
# i1, i2 = hessian_matrix_eigvals(hxx, hxy, hyy)
# show_one_img(i1)
# show_one_img(i2)
# hog działa za wolno
# from skimage.feature import hog
# fd, hog_image = hog(morph_img, orientations=9, pixels_per_cell=(20, 20),
# cells_per_block=(1, 1), visualize=True, multichannel=True)
# show_one_img(hog_image)
# Morphological operations can be used without denoising - but part of the data can be lost
def morphology_filter():
morph_img = load_a_picture()
kernel = ([0, 1, 0],
[0, 0, 0],
[0, 0, 0])
kernel = np.uint8(kernel)
kernel_dil = np.ones((3, 3), np.uint8)
kernel_ero = np.ones((7, 7), np.uint8)
if len(morph_img.shape) >= 3:
try:
#### TEST
print("***converting to grayscale***")
morph_for_ski = ((color.rgb2gray(morph_img)) * 255).astype(np.uint8)
wth = white_tophat(morph_img)
show_one_img(wth)
filter = np.logical_or(wth[:, :, 0] > 5, wth[:, :, 1] > 5)
filter = np.logical_or(filter, wth[:, :, 2] > 5)
morph_for_ski[filter] = 0
add_to_stack(morph_for_ski)
show_img(actual_loaded)
processing_menu()
#### TEST
print("***converting to grayscale***")
morph_for_ski = img_as_float(color.rgb2gray(morph_img))
# binearisation
image_binary = morph_for_ski > 0.001
org = image_binary # onlly to compare with edited
morph_for_ski[np.logical_not(image_binary)] = 0
show_one_img(morph_for_ski)
# binearization - Black tophat
wth = white_tophat(morph_img)
# bth = black_tophat(morph_for_ski)#> 0.001
ch_one = wth[:, :, 0] > 5
ch_two = wth[:, :, 1] > 5
ch_three = wth[:, :, 2] > 5
morph_for_ski[ch_one] = 0
morph_for_ski[ch_two] = 0
morph_for_ski[ch_three] = 0
letsee = 2 * org + 4 * morph_for_ski
# show_one_img(morph_for_ski)
# show_one_img(wth[:, :, 0])
# show_one_img(wth[:, :, 1])
# show_one_img(wth[:, :, 2])
show_one_img(letsee)
image_binary = morphology.opening(morph_for_ski)
image_binary = cv2.dilate(np.float32(morph_for_ski), kernel_dil, iterations=3)
out_skel = skeletonize(image_binary, method='lee')
# out_thin = thin(image_binary)
# show_one_img(image_binary + out_skel + out_thin)
outlet = 5 * letsee + out_skel
show_one_img(outlet)
add_to_stack(out_skel)
show_img(actual_loaded)
processing_menu()
# openinig = morphology.opening(image_binary)
# show_one_img(openinig)
# closeing = morphology.closing(openinig)
# closeing = morphology.closing(closeing)
# show_one_img(image_binary + 0.3 * closeing)
# out_thin = morphology.skeletonize(closeing)
# show_one_img(out_thin)
# img_dil = cv2.dilate(np.float32(image_binary), kernel_dil, iterations=5)
# out_thin = skeletonize(openinig, method='lee')
# show_one_img(out_thin)
# letsee = image_binary + out_thin
# show_one_img(letsee)
# add_to_stack(out_thin)
# show_img(actual_loaded)
# processing_menu()
# show_one_img(distance)
# show_one_img(letsee)
# from scipy import ndimage as ndi
# mask = ndimage.binary_fill_holes(openinig).astype(int)
# show_one_img(mask)
# out_thin = morphology.skeletonize(mask)
# show_one_img(out_thin)
# skel, distance = morphology.medial_axis(closeing, return_distance=True)
# letsee = distance * skel
# show_one_img(distance)
# show_one_img(letsee)
# show_one_img(image_binary)
# img_dilation = cv2.dilate(np.float32(image_binary), kernel_dil, iterations=5)
# show_one_img(img_dilation)
# out_thin = morphology.thin(img_dilation)
# show_one_img(out_thin)
# img_erosion = cv2.erode(np.float32(img_dilation), kernel_ero, iterations=2)
# show_one_img(img_erosion)
# out_thin = morphology.thin(img_erosion)
# show_one_img(out_thin)
# plus = 0.3 * image_binary + img_dilation + 10 * out_thin
# show_one_img(plus)
# add_to_stack(out_thin)
# show_img(actual_loaded)
# processing_menu()
# img_dilation = cv2.dilate(np.float32(image_binary), kernel, iterations=2)
# show_one_img(img_dilation)
# img_erosion = cv2.erode(np.float32(img_dilation), kernel, iterations=1)
# show_one_img(img_erosion)
# img_dilation = cv2.dilate(img_erosion, kernel, iterations=2)
# show_one_img(img_dilation)
# img_dilation = cv2.dilate(img_dilation, kernel, iterations=2)
# show_one_img(img_dilation)
# img_erosion = cv2.erode(img_dilation, kernel, iterations=1)
# show_one_img(img_erosion)
# out_thin = morphology.thin(img_dilation)
# show_one_img(out_thin)
# out_skeletonize = morphology.skeletonize(img_dilation)
# show_one_img(out_skeletonize)
# add_to_stack(out_thin)
# show_img(actual_loaded)
# processing_menu()
except ValueError:
print(ValueError)
print("Can't convert this image to grayscale")
input("press any key to back to processing menu...")
processing_menu()
# good work with denoising, gamma, sv from hsv and knee filtering
# this is much more precisly but, takes much longer time
else:
try:
print("***Collecting data..***")
morph_for_ski = img_as_float(morph_img)
# binearisation
image_binary = morph_for_ski > 0.001
org = image_binary # onlly to compare with edited
morph_for_ski[np.logical_not(image_binary)] = 0
# show_one_img(morph_for_ski)
# binearization - Black tophat
# wth = white_tophat(morph_img)
# show_one_img(wth)
image_binary = morphology.opening(morph_for_ski)
image_binary = cv2.dilate(np.float32(image_binary), kernel_dil, iterations=3)
out_skel = skeletonize(image_binary, method='lee')
add_to_stack(out_skel)
show_img(actual_loaded)
processing_menu()
# image_binary = morph_img > 0.001
# out_thin = morphology.thin(image_binary)
# openinig = morphology.opening(image_binary)
# show_one_img(openinig)
# out_thin = morphology.skeletonize(openinig)
# show_one_img(out_thin)
# letsee = 0.3 * image_binary * out_thin
# show_one_img(letsee)
# closeing = morphology.closing(openinig)
# show_one_img(closeing)
# out_thin = morphology.skeletonize(closeing)
# show_one_img(out_thin)
#
# letsee = 0.3 * image_binary * out_thin
# show_one_img(letsee)
# add_to_stack(out_thin)
# show_img(actual_loaded)
processing_menu()
except ValueError:
print(ValueError)
print("Can't plot this image...")
input("press any key to back to processing menu...")
processing_menu()
##morph_for_ski = img_as_float(color.rgb2gray(morph_img))
# show_one_img(morph_for_ski)
##image_binary = morph_for_ski > 0.01
# show_one_img(image_binary)
# out_skeletonize = morphology.skeletonize(image_binary)
# show_one_img(out_skeletonize)
##out_thin = morphology.thin(image_binary)
# show_one_img(out_thin)
##add_to_stack(out_thin)
##show_img(actual_loaded)
##processing_menu()
# morph_img = cv2.cvtColor(morph_img, cv2.COLOR_BGR2GRAY)
morph_kernel = ([0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 0, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 0, 0, 0]) # np.ones((10, 10), np.uint8)
# ([0, 0, 0, 0, 1, 0, 0, 0, 0],
# [0, 0, 0, 0, 1, 0, 0, 0, 0],
# [0, 0, 0, 1, 1, 1, 0, 0, 0],
# [0, 0, 0, 1, 1, 1, 0, 0, 0],
# [0, 0, 0, 1, 1, 1, 0, 0, 0],
# [0, 0, 0, 1, 1, 1, 0, 0, 0],
# [0, 0, 0, 1, 1, 1, 0, 0, 0],
# [0, 0, 1, 1, 1, 1, 1, 0, 0],
# [0, 1, 1, 1, 1, 1, 1, 1, 0])
# morph_erosion = cv2.erode(morph_img, morph_kernel, iterations=1)
# morph_dilation = cv2.dilate(morph_img, morph_kernel, iterations=1)
# morph_opening = cv2.morphologyEx(morph_img, cv2.MORPH_OPEN, morph_kernel)
# morph_closing = cv2.morphologyEx(morph_img, cv2.MORPH_CLOSE, morph_kernel)
# morph_gradient = cv2.morphologyEx(morph_img, cv2.MORPH_GRADIENT, morph_kernel)
##morph_tophat = cv2.morphologyEx(morph_img, cv2.MORPH_TOPHAT, np.uint8(morph_kernel))
##morph_blackhat = cv2.morphologyEx(morph_img, cv2.MORPH_BLACKHAT, np.uint8(morph_kernel))
# fro displaying the image
# show_one_img(morph_erosion)
# show_one_img(morph_dilation)
# show_one_img(morph_opening)
# show_one_img(morph_closing)
# show_one_img(morph_gradient)
# show_one_img(morph_tophat)
# show_one_img(morph_blackhat)
# Adding to the stack of images
def add_to_stack(img_to_add):
print(len(img_list))
# Convert image to np ndarray class
img_array_to_add = np.asarray(img_to_add)
global actual_loaded
# Check if loaded image is the last one on the stack or is there oly original image
if actual_loaded + 1 == len(img_list) or len(img_list) == 1:
img_list.append(img_array_to_add)
actual_loaded = actual_loaded + 1
print(len(img_list))
# If not edited image will be add as next to loaded, all higher will be deleted
else:
img_list[actual_loaded + 1] = img_array_to_add
actual_loaded = actual_loaded + 1
len_of_img_stack = len(img_list)
if actual_loaded + 1 < len_of_img_stack:
del img_list[-(len_of_img_stack - (actual_loaded + 1)):]
print(len(img_list))
# Undo last image edit
def undo_edit():
global actual_loaded
if actual_loaded > 0:
choices.undo_choice() # remove last function
actual_loaded = actual_loaded - 1
show_img(actual_loaded)
else:
print("Can't undo.")
processing_menu()
# Redo last image edit
def redo_edit():
global actual_loaded
if 0 <= actual_loaded < len(img_list) - 1:
choices.redo_choice() # Readd last deleted function to the list
actual_loaded = actual_loaded + 1
show_img(actual_loaded)
else:
print("Can't redo.")
processing_menu()
# save picture to orginal destination
def save_picture():
img_to_save = load_a_picture()
head, tail = os.path.split(new_path)
file_path = head + '\edited_' + tail
print(file_path)
cv2.imwrite(file_path, img_to_save)
# Load image as HSV
def rgb_to_hsv():
img_to_hsv = np.asarray(load_a_picture())
if len(img_to_hsv.shape) >= 3:
try:
img_to_hsv = img_list[actual_loaded]
hsv = cv2.cvtColor(img_to_hsv, cv2.COLOR_BGR2HSV)
add_to_stack(hsv)
hsv_processing_menu()
except ValueError:
print(ValueError)
print("Can't convert to hsv, try undo.")
input("press any key to back to processing menu...")
processing_menu()
else:
print("Can't convert rgb to hsv.")
# Normalise an image
def normalise_img():
img_to_normalise = load_a_picture()
img_to_normalise_out = np.zeros((img_to_normalise.shape[0], img_to_normalise.shape[1]))
img_to_normalise = cv2.normalize(img_to_normalise, img_to_normalise_out, 0, 255, cv2.NORM_MINMAX)
add_to_stack(img_to_normalise)
show_img(actual_loaded)
processing_menu()
# Filtering specific channel of HSV using standard deviation
def sf_filter(img_stat, factor):
mean = np.mean(img_stat)
std_dev = np.std(img_stat)
print("mean:%s Std:%s" % (mean, std_dev))
img_to_show = img_stat > mean + (float(factor) * std_dev)
show_one_img(img_to_show)
hsv_processing_menu()
# Ask for rgb filtering range
def prepare_rgb_range():
print("Please insert RGB filtering range... (0-255) ")
while True:
try:
r_min = int(input("R minimum: "))
break