-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathMainFileGUI.py
More file actions
2568 lines (2043 loc) · 120 KB
/
MainFileGUI.py
File metadata and controls
2568 lines (2043 loc) · 120 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
import sys
from PyQt5.QtWidgets import ( QCheckBox,QScrollArea, QGridLayout, QFrame, QSpinBox, QComboBox, QLineEdit, QPushButton, QVBoxLayout, QHBoxLayout, QApplication, QWidget, QLabel, QFileDialog, QDialog)
import os
import time
from datetime import timedelta
import numpy as np
import cv2
import csv
from FunctionToCreateTrainingData import TrainingData
from FunctionForSegmentation import Segmentation
from FunctionToSelectROI import SelectROI
import ast
from random import randint
class TrainingWindow(QDialog):
""" This class contain the GUI for the window used to create the training data.
This window can be opened from the class 'MainWindow' by clicking on the button 'Create new set of training data' (MainWindow.button_newTrainingData)
This class has two parameters:
WorkingDirectory (string):
Address of the working directory
(ex: WorkingDirectory='/Users/Name/Desktop/folder'
DisplaySize (int):
Integer use to calculate the resizing coefficient for the display of the pictures
(ex: displaySize=500)
"""
def __init__(self, parent=None, workingDirectory=None, DisplaySize=None):
super(TrainingWindow, self).__init__(parent)
self.displaySize=DisplaySize
self.workingDirectory = workingDirectory
self.classes=2
self.init_TrainingWindow()
def init_TrainingWindow(self):
"""Function to set up the GUI and link the buttons to their corresponding functions """
#Name the window
self.setWindowTitle('Create training data')
#Create all the widgets
self.label_newTrainingDataInfo = QLabel('When you press start, the first picture will appear. \n First select some pixels of the foreground/plant which will appear in red. \n When you are done, press "E" on your keyboard and select a few pixels of the background. \n When your are done press "e" again to save the data and press the space bar to pass to the next picture. \n Repeat until all the pictures have been annotated. ')
self.label_newTrainingData = QLabel('Choose the pictures you want to use for creating the training data :')
self.label_ModeTrainingPictures = QLabel('Mode:')
self.label_NumberPictures = QLabel('Path to the training pictures:')
self.text_SelectTrainingPicture = QLabel()
self.button_ListImages=QPushButton('Show the whole List',default=False, autoDefault=False)
self.button_SelectTrainingPictures = QPushButton('Look for some picture(s)', default=False, autoDefault=False)
self.button_SelectTrainingPicturesDirectory= QPushButton('Look for a directory', default=False, autoDefault=False)
self.clear_button = QPushButton('Clear', default=False, autoDefault=False)
self.label_empty = QLabel() #just to help with the layout
self.label_NumberOfClasses = QLabel('Choose the number of classes you want to use:')
self.spinbox_numberOfClasses = QSpinBox()
self.spinbox_numberOfClasses.setMinimum(2)
self.spinbox_numberOfClasses.setMaximum(5)
self.spinbox_numberOfClasses.setValue(2)
self.button_NameClasses=QPushButton('Name the classes',default=False, autoDefault=False)
self.label_NameClasses = QLabel('')
self.cancel_button = QPushButton('Cancel', default=False, autoDefault=False)
self.button_newTrainingDataStart = QPushButton('START',default=False, autoDefault=False)
#Create the layout
h_box1 = QHBoxLayout()
h_box1.addWidget(self.button_SelectTrainingPicturesDirectory)
h_box1.addWidget(self.button_SelectTrainingPictures)
h_box1.addWidget(self.clear_button)
h_boxbutton = QHBoxLayout()
h_boxbutton.addWidget(self.cancel_button)
h_boxbutton.addWidget(self.button_newTrainingDataStart)
h_boxclasses = QHBoxLayout()
h_boxclasses.addWidget(self.label_NumberOfClasses)
h_boxclasses.addWidget(self.spinbox_numberOfClasses)
h_boxclasses.addWidget(self.button_NameClasses)
v_box = QVBoxLayout()
v_box.addWidget(self.label_newTrainingData)
v_box.addWidget(self.label_ModeTrainingPictures)
v_box.addWidget(self.label_NumberPictures)
v_box.addWidget(self.text_SelectTrainingPicture)
v_box.addWidget(self.button_ListImages)
v_box.addLayout(h_box1)
v_box.addWidget(self.label_empty)
v_box.addLayout(h_boxclasses)
v_box.addWidget(self.label_NameClasses)
v_box.addLayout(h_boxbutton)
self.setLayout(v_box)
self.show()
self.button_ListImages.hide()
# Link the buttons and spinbox to their corresponding functions
self.button_ListImages.clicked.connect(self.ShowListImages)
self.button_SelectTrainingPictures.clicked.connect(self.lookForTrainingPicture)
self.button_SelectTrainingPicturesDirectory.clicked.connect(self.lookForTrainingPictureDirectoryFunction)
self.clear_button.clicked.connect(self.clear_text)
self.button_newTrainingDataStart.clicked.connect(self.CreateTrainingData)
self.cancel_button.clicked.connect(self.cancel)
self.button_NameClasses.clicked.connect(self.NameClassesFunction)
self.spinbox_numberOfClasses.valueChanged.connect(self.spinboxChangedFunction)
#Initialize the different variables
self.newfilecreated='N'
self.listPictureNames=[]
self.classesNamesList=[]
self.classes=self.spinbox_numberOfClasses.value()
for i in range(self.classes):
self.classesNamesList.append('Class_'+str(i+1))
self.label_NameClasses.setText(self.label_NameClasses.text()+'Class '+str(i+1)+': '+self.classesNamesList[i]+'\n')
def spinboxChangedFunction(self):
""" This function is part of the class 'TrainingWindow'. \n
It is linked to the change of value of the spinbox self.spinbox_numberOfClasses. \n
When the value of the spinbox changes, the attribute self.classes changes according to the value of the spinbox and the label self.label_NameClasses changes. """
self.label_NameClasses.setText('')
self.classesNamesList=[]
self.classes=self.spinbox_numberOfClasses.value()
for i in range(self.classes):
self.classesNamesList.append('Class_'+str(i+1))
self.label_NameClasses.setText(self.label_NameClasses.text()+'Class '+str(i+1)+': '+self.classesNamesList[i]+'\n')
def ShowListImages(self):
""" This function is part of the class 'TrainingWindow'. \n
It is linked to the click of the button 'Show the whole list' (self.button_ListImages) \n
When the button is clicked, the window 'ListNameWindow' is opened"""
ListWin=ListNameWindow(parent=self, List=self.listPictureNames)
ListWin.exec_()
def lookForTrainingPicture(self):
""" This function is part of the class 'TrainingWindow'. \n
It is linked to the click of the button 'Look for some picture(s)' (self.button_SelectTrainingPictures) \n
This function allow the user to choose one or several pictures which will be used to create the training data set."""
self.button_ListImages.hide()
self.text_SelectTrainingPicture.setText('')
#Open a dialog window to choose the pictures
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
self.listPictureNames, _ = QFileDialog.getOpenFileNames(self,"Select the training picture(s)", "",".png or jpg (*.png *.jpg *.JPG *.jpeg)", options=options)
if self.listPictureNames: #if the user has selected at least 1 file
for i in range(len(self.listPictureNames)): #Only display the first 5 file addresses
if i<5:
self.text_SelectTrainingPicture.setText(self.text_SelectTrainingPicture.text()+'\n'+str(self.listPictureNames[i]))
if i==5 and len(self.listPictureNames)>5:
self.text_SelectTrainingPicture.setText(self.text_SelectTrainingPicture.text()+'\n ...')
if len(self.listPictureNames)>5: #If more than 5 pictures are selected, the button 'Show the whole List' (self.button_ListImages) appears and allow the user to see the whole list in another window.
self.button_ListImages.show()
self.label_ModeTrainingPictures.setText('Mode: Files')
#Count the number of picture
if len(self.listPictureNames)==0 or len(self.listPictureNames)==1:
self.label_NumberPictures.setText('Path to the training pictures: ('+str(len(self.listPictureNames))+' picture)')
else :
self.label_NumberPictures.setText('Path to the training pictures: ('+str(len(self.listPictureNames))+' pictures)')
def lookForTrainingPictureDirectoryFunction(self):
""" This function is part of the class 'TrainingWindow'. \n
It is linked to the click of the button 'Look for a directory' (self.button_SelectTrainingPicturesDirectory) \n
This function allow the user to choose one directory containing the pictures which will be used to create the training data set."""
#Open a dialog window to choose the pictures
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
DirectoryName= str(QFileDialog.getExistingDirectory(self, "Select Directory with the training picture(s)"))
if DirectoryName!='': #if the user has selected a directory
self.text_SelectTrainingPicture.setText(DirectoryName)
self.label_ModeTrainingPictures.setText('Mode: Directory')
#Save the list of the addresses of the pictures in the directory in self.listPictureNames
ListImageinDirectory=os.listdir(DirectoryName)
ListImage=[]
for i in range(len(ListImageinDirectory)):
a=ListImageinDirectory[i].split('.')
if 'jpeg'in a or 'png'in a or 'jpg'in a or 'JPG' in a: #only take the images
ListImage.append(DirectoryName+'/'+ListImageinDirectory[i])
self.listPictureNames=ListImage
#Count the number of picture
if len(self.listPictureNames)==0 or len(self.listPictureNames)==1:
self.label_NumberPictures.setText('Path to the directory: ('+str(len(self.listPictureNames))+' picture)')
else :
self.label_NumberPictures.setText('Path to the directory: ('+str(len(self.listPictureNames))+' pictures)')
self.button_ListImages.show() #the button 'Show the whole List' (self.button_ListImages) appears and allow the user to see the list of the pictures in the directory in another window.
def clear_text(self):
""" This function is part of the class 'TrainingWindow'. \n
It is linked to the click of the button 'Clear' (self.clear_button) \n
Erase the content of the label self.text_SelectTrainingPicture"""
self.label_NumberPictures.setText('Path to the training pictures:')
self.text_SelectTrainingPicture.clear()
self.listPictureNames=[]
def cancel(self):
""" This function is part of the class 'TrainingWindow'. \n
It is linked to the click of the button 'Cancel' (self.cancel_button) \n
Close the window without saving any file """
self.newfilecreated='N'
self.ListTrainingDataFile=[]
self.hide()
def NameClassesFunction(self):
""" This function is part of the class 'TrainingWindow'. \n
It is linked to the click of the button 'Name the classes' (self.button_NameClasses) \n
Open a new window from the class 'WindowNameClasses' and save the name chosen in this window"""
self.classes=self.spinbox_numberOfClasses.value()
#Open the window
WindNames=WindowNameClasses(parent=self, classes=self.classes, classesNamesList=self.classesNamesList)
WindNames.exec_()
#Save the names in self.classesNamesList and display them inthe label self.label_NameClasses
self.classesNamesList=WindNames.NamesList
self.label_NameClasses.setText('')
for i in range(self.classes):
self.label_NameClasses.setText(self.label_NameClasses.text()+'Class '+str(i+1)+': '+self.classesNamesList[i]+'\n')
def CreateTrainingData(self):
""" This function is the main function of the class 'TrainingWindow'. \n
It is linked to the click of the button 'START' (self.button_newTrainingDataStart) \n
Use the function 'SelectOneClass' of the class 'TrainingData' from the file FunctionToCreateTrainingData.py"""
#Error message if one of the parameter is missing
if self.listPictureNames==[] or self.label_NumberPictures.text()=='Path to the directory: (0 picture)':
messageWin=MessageWindow(parent=self, WorkingDirectory='OK', trainingData='OK', listPictureNames='OK', ROI='OK', text_InfoTestPictures='OK', trainingDataPicture=[], NamesList='Y', selectedpixels='Y',Window='N')
messageWin.exec_()
else :
self.ListTrainingDataFile=[]
# Create the directory where the output will be saved
TrainingDataDirectory=self.workingDirectory+'/TrainingData'
if not os.path.exists(TrainingDataDirectory):
os.mkdir(TrainingDataDirectory)
colorList=[(0,0,255),(0,255,0),(255,0,0),(0,255,255),(255,0,255)] # 5 different colors, one for each class
for i in range(self.classes):
#Open a small window explaining what to do
InfoWin=InfoWindowTrainindData(parent=None, Class=self.classesNamesList[i])
InfoWin.exec_()
#Call the function for each class
t=TrainingData()
ListFile=TrainingData.SelectOneClass(t,self.listPictureNames,TrainingDataDirectory,self.classesNamesList[i],colorList[i],self.displaySize)
self.ListTrainingDataFile.extend(ListFile)
#Error message if no pixels have been selected
if self.ListTrainingDataFile==[]:
messageWin=MessageWindow(parent=self, WorkingDirectory='OK', trainingData='OK', listPictureNames='OK', ROI='OK', text_InfoTestPictures='OK', trainingDataPicture='OK', NamesList='Y', selectedpixels='N', Window='N')
messageWin.exec_()
#Save a file compiling all the individual training data files for easier use
else:
self.newfilecreated='Y'
trainDataTab=np.array([[0,0,0,0,0,0,0,0,0,0,0,0,0]])
for file in self.ListTrainingDataFile:
f=open(file,"r",newline='')
TrainData = list(csv.reader(f))
f.close()
TrainData.remove(['Class', 'Image', 'x','y','B','G','R','H','S','V','L','a','b'])
TrainData=np.asarray(TrainData)
trainDataTab=np.concatenate((trainDataTab, TrainData), axis=0)
trainDataTab=np.delete(trainDataTab, (0), axis=0)
np.savetxt(TrainingDataDirectory+'/trainData_'+str(self.classes)+'classes.csv', trainDataTab, delimiter=",",header='Class,Image,x,y,B,G,R,H,S,V,L,a,b', comments='',fmt='%s')
self.ListTrainingDataFile=[TrainingDataDirectory+'/trainData_'+str(self.classes)+'classes.csv']
#Last message window to inform the user that all the pictures for all the class have been red.
InfoWin2=YourDoneWindow(parent=None, Name=TrainingDataDirectory+'/trainData_'+str(self.classes)+'classes.csv')
InfoWin2.exec_()
#Close the training data window and go back to the main window
self.hide()
class InfoWindowTrainindData(QDialog):
""" This class contain the GUI for a message window.
This window will be opened from the class 'TrainingWindow' by the function red when the button 'START' (MainWindow.button_newTrainingDataStart) is pushed. \n
This class has one parameter:
Class (string):
Name of the class for which the user is going to select pixels
(ex: Class='PaddyRice')
"""
def __init__(self, parent=None, Class=None):
super(InfoWindowTrainindData, self).__init__(parent)
self.Class=Class
self.init_InfoWindowTrainindData()
def init_InfoWindowTrainindData(self):
#Name the window
self.setWindowTitle('Tutorial')
#Create the widgets
self.button_close = QPushButton('OK')
self.label_Info = QLabel('Select some pixels for the class: '+ str(self.Class) +'\n Press "E" when you are done to go to the next picture \n Press "Q" if you want to start the picture again')
#Create the layout
v_box=QVBoxLayout()
v_box.addWidget(self.label_Info)
v_box.addWidget(self.button_close)
self.setLayout(v_box)
self.show()
#connect the button to its function
self.button_close.clicked.connect(self.close)
def close(self):
# Function to close this window
self.hide()
class YourDoneWindow(QDialog):
""" This class contain the GUI for a message window.
This window will be opened from the class 'TrainingWindow' by the function red when the button 'START' (MainWindow.button_newTrainingDataStart) is pushed. \n
This class has one parameter:
Name (string):
Address of the compiled training data file
(ex: Name='/Users/Name/Desktop/folder/TrainingData/trainData_2classes.csv')
"""
def __init__(self, parent=None, Name=None):
super(YourDoneWindow, self).__init__(parent)
self.Name=Name
self.init_InfoWindowTrainindData()
def init_InfoWindowTrainindData(self):
#Name the window
self.setWindowTitle('Info')
#Create the widgets
self.button_close = QPushButton('OK')
self.label_Info = QLabel('You are done ! \n The training data file has been saved at the address: \n'+ str(self.Name))
#Create the layout
v_box=QVBoxLayout()
v_box.addWidget(self.label_Info)
v_box.addWidget(self.button_close)
self.setLayout(v_box)
self.show()
#connect the button to its function
self.button_close.clicked.connect(self.close)
def close(self):
# Function to close this window
self.hide()
class WindowNameClasses(QDialog):
""" This class contain the GUI for the window used to give a name to the classes. \n
This window can be opened from class 'TrainingWindow' by clicking on the button 'Name the classes' (self.button_NameClasses) \n
This class has two parameters:
classes (int):
Number of classes
(ex: classes=2)
classesNamesList (List of strings):
List of the names of the classes
(ex: classesNamesList=['PaddyRice','Background'] )
"""
def __init__(self, parent=None, classes=None, classesNamesList=None):
super(WindowNameClasses, self).__init__(parent)
self.classes=classes
self.classesNamesList=classesNamesList
self.init_WindowNameClasses()
def init_WindowNameClasses(self):
#Name the window
self.setWindowTitle('Name the classes')
#Initialize the lists
self.NamesList=[]
self.Line=[]
self.InitNameList=[]
#Create the widgets
self.label_Info = QLabel('Choose a name for each class (No space):')
for i in range(self.classes):
label = QLabel('Class '+str(i+1))
LineEdit= QLineEdit(self.classesNamesList[i])
h_box=QHBoxLayout()
h_box.addWidget(label)
h_box.addWidget(LineEdit)
self.Line.append(h_box)
self.InitNameList.append(LineEdit)
self.button_close = QPushButton('OK')
#Create the layout
v_box=QVBoxLayout()
v_box.addWidget(self.label_Info)
for line in self.Line:
v_box.addLayout(line)
v_box.addWidget(self.button_close)
self.setLayout(v_box)
self.show()
#connect the button to its function
self.button_close.clicked.connect(self.close)
def close(self):
# Function to close this window
self.NamesList=[]
for i in range(self.classes):
name=self.InitNameList[i].text()
self.NamesList.append(name)
#Error message if one classes has no name
if '' in self.NamesList:
messageWin=MessageWindow(parent=self, WorkingDirectory='OK', trainingData='OK', listPictureNames='OK', ROI='OK', text_InfoTestPictures='OK', trainingDataPicture='OK', NamesList='Class', selectedpixels='Y', Window='N')
messageWin.exec_()
else:
self.hide()
#####################################################################################################################################
#####################################################################################################################################
#####################################################################################################################################
class DirectoryWindow(QDialog):
""" This class contain the GUI for the window used to create a new directory.
This window can be opened from the class 'MainWindow' by clicking on the button 'Create a new directory' (MainWindow.button_CreateNewWorkingDirectory)
"""
def __init__(self, parent=None):
super(DirectoryWindow, self).__init__(parent)
self.init_DirectoryWindow()
def init_DirectoryWindow(self):
#Name the window
self.setWindowTitle('Create a new Directory')
####First Part : default layout
#Create the widgets
self.label_newWorkingDirectory = QLabel('Choose the directory where you want to Create the Directory and its name:')
self.label_empty = QLabel() #just to help with the layout
self.text_newWorkingDirectoryPath = QLabel('Directory/')
self.button_newWorkingDirectoryPath = QPushButton('Choose the path', default=False, autoDefault=False)
self.clear_button = QPushButton('Clear', default=False, autoDefault=False)
self.cancel_button = QPushButton('Cancel', default=False, autoDefault=False)
self.text_newWorkingDirectoryName = QLineEdit()
self.label_newWorkingDirectoryName = QLabel('Choose the name of the Directory')
self.button_newWorkingDirectorySave = QPushButton('SAVE', default=False, autoDefault=False)
#Create the layout
v_boxlabel = QVBoxLayout()
v_boxlabel.addWidget(self.label_newWorkingDirectory)
v_boxlabel.addWidget(self.label_empty)
v_boxPath = QVBoxLayout()
v_boxPath.addWidget(self.text_newWorkingDirectoryPath)
v_boxPath.addWidget(self.button_newWorkingDirectoryPath)
v_boxName = QVBoxLayout()
v_boxName.addWidget(self.text_newWorkingDirectoryName)
v_boxName.addWidget(self.label_newWorkingDirectoryName)
h_box = QHBoxLayout()
h_box.addLayout(v_boxlabel)
h_box.addLayout(v_boxPath)
h_box.addLayout(v_boxName)
h_boxButton=QHBoxLayout()
h_boxButton.addWidget(self.cancel_button)
h_boxButton.addWidget(self.clear_button)
h_boxButton.addWidget(self.button_newWorkingDirectorySave)
v_box = QVBoxLayout()
v_box.addLayout(h_box)
v_box.addLayout(h_boxButton)
self.windowlayout=v_box
#connect the button to its function
self.clear_button.clicked.connect(self.clear_text)
self.button_newWorkingDirectoryPath.clicked.connect(self.ChooseWorkingDirectoryPathFunction)
self.button_newWorkingDirectorySave.clicked.connect(self.CreateNewWorkingDirectoryFunction)
self.cancel_button.clicked.connect(self.cancel)
####Second Part : layout with warnings
#Create the widgets
self.label_NoPath = QLabel('Please enter the path of the Directory')
self.label_Confimation = QLabel('')
self.button_ConfirmationYes = QPushButton('Yes')
self.button_ConfirmationNo = QPushButton('No', default=False, autoDefault=False)
#Create the layout
self.h_boxConfirmation=QHBoxLayout()
self.h_boxConfirmation.addWidget(self.label_NoPath)
self.h_boxConfirmation.addWidget(self.label_Confimation)
self.h_boxConfirmation.addWidget(self.button_ConfirmationYes)
self.h_boxConfirmation.addWidget(self.button_ConfirmationNo)
self.windowlayout.addLayout(self.h_boxConfirmation)
#connect the buttons to their function
self.button_ConfirmationYes.clicked.connect(self.button_ConfirmationYesFunction)
self.button_ConfirmationNo.clicked.connect(self.button_ConfirmationNoFunction)
#Hide the warnings as long as they are not needed
self.label_NoPath.hide()
self.label_Confimation.hide()
self.button_ConfirmationYes.hide()
self.button_ConfirmationNo.hide()
self.label_ChooseAnotherName = QLabel('Please choose another name')
self.windowlayout.addWidget(self.label_ChooseAnotherName)
self.label_ChooseAnotherName.hide()
#Set and show the layout in the window
self.setLayout(self.windowlayout)
self.show()
def ChooseWorkingDirectoryPathFunction(self):
""" This function is part of the class 'DirectoryWindow'. \n
It is linked to the click of the button 'Choose the path' (self.button_newWorkingDirectoryPath) \n
This function allow the user to choose one directory where the new directory will be saved."""
#Open a dialog window to choose the directory
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
DirectoryName= str(QFileDialog.getExistingDirectory(self, "Select a directory"))
#Print the address in the label self.text_newWorkingDirectoryPath
self.text_newWorkingDirectoryPath.setText(DirectoryName)
def CreateNewWorkingDirectoryFunction(self):
""" This function is part of the class 'DirectoryWindow'. \n
It is linked to the click of the button 'SAVE' (self.button_newWorkingDirectorySave) \n
This function Creates a new directory at the chosen address."""
NewDirectoryName=self.text_newWorkingDirectoryPath.text()+'/'+ self.text_newWorkingDirectoryName.text()
#Error message if no address or name have been chosen
if self.text_newWorkingDirectoryPath.text()=='Directory/' or self.text_newWorkingDirectoryPath.text()=='':
self.label_NoPath.show()
else :
#Create the directory if it doesn't already exist
self.label_NoPath.hide()
if not os.path.exists(NewDirectoryName):
os.mkdir(NewDirectoryName)
self.hide()
#If it already exists, warning message appears
if os.path.exists(NewDirectoryName):
self.label_Confimation.show()
self.label_Confimation.setText('The Directory '+ self.text_newWorkingDirectoryPath.text()+'/'+ self.text_newWorkingDirectoryName.text()+' already exist. Would you like to use it ?')
self.button_ConfirmationYes.show()
self.button_ConfirmationNo.show()
def button_ConfirmationYesFunction(self):
""" This function is part of the class 'DirectoryWindow'. \n
It is linked to the click of the button 'Yes' (self.button_ConfirmationYes) \n
This function keep the chosen address and close the window."""
self.hide()
def button_ConfirmationNoFunction(self):
""" This function is part of the class 'DirectoryWindow'. \n
It is linked to the click of the button 'No' (self.button_ConfirmationNo) \n
This function clear the chosen address and display a message asking to choose another name."""
self.label_Confimation.hide()
self.button_ConfirmationYes.hide()
self.button_ConfirmationNo.hide()
self.label_ChooseAnotherName.show()
self.text_newWorkingDirectoryName.clear()
def clear_text(self):
""" This function is part of the class 'DirectoryWindow'. \n
It is linked to the click of the button 'Clear' (self.clear_button) \n
This function clear the chosen address """
self.text_newWorkingDirectoryPath.clear()
self.text_newWorkingDirectoryName.clear()
def cancel(self):
""" This function is part of the class 'DirectoryWindow'. \n
It is linked to the click of the button 'Cancel' (self.cancel_button) \n
Close the window without saving any address """
self.text_newWorkingDirectoryPath.clear()
self.text_newWorkingDirectoryName.clear()
self.hide()
#####################################################################################################################################
#####################################################################################################################################
#####################################################################################################################################
class RegionOfInterestWindow(QDialog):
""" This class contain the GUI for the window used to choose the regions of interest (ROI). \n
This window can be opened from the class 'MainWindow' by clicking on the button 'Select one or several ROI' (MainWindow.button_RegionOfInterest) \n
This class has three parameters:
WorkingDirectory (string):
Address of the working directory
(ex: WorkingDirectory='/Users/Name/Desktop/folder')
ListImageName (List of strings):
List of the addresses of all the pictures that the user wants to process.
(ex: ListImageName=['/Users/Name/Desktop/image.png','/Users/Name/Desktop/image2.png','/Users/Name/Desktop/image3.png'])
DisplaySize (int):
Integer use to calculate the resizing coefficient for the display of the pictures
(ex: displaySize=500)
"""
def __init__(self, parent=None, workingDirectory=None, ImageNames=None, DisplaySize=None):
super(RegionOfInterestWindow, self).__init__(parent)
self.displaySize=DisplaySize
self.ImageNames = ImageNames
if '.DS_Store' in self.ImageNames:
self.ImageNames.remove('.DS_Store')
self.workingDirectory=workingDirectory
self.init_RegionOfInterestWindow()
def init_RegionOfInterestWindow(self):
#Name the window
self.setWindowTitle('Select one or several Regions of interest (ROI)')
# Create the widgets
self.label_Info = QLabel('Select the Region(s) of Interest and choose if you want to save the cropped pictures. \n Note: saving the cropped pictures might take a lot of space and time if you are using \n big and/or many pictures')
self.label_NbROI = QLabel('Coordinates of the selected region(s): ')
self.button_start=QPushButton('Select the area(s)', default=False, autoDefault=False)
self.button_center=QPushButton('Use the center', default=False, autoDefault=False)
self.label_center=QLabel('Pourcentage of the image:')
self.spinbox_center = QSpinBox()
self.spinbox_center.setMinimum(5)
self.spinbox_center.setMaximum(100)
self.spinbox_center.setSingleStep(5)
self.spinbox_center.setValue(50)
self.spinbox_center.hide()
self.label_center.hide()
h_boxCenter=QHBoxLayout()
h_boxCenter.addWidget(self.label_center)
h_boxCenter.addWidget(self.spinbox_center)
self.button_random=QPushButton('Choose random rectangle', default=False, autoDefault=False)
self.spinbox_nbRandom = QSpinBox()
self.spinbox_nbRandom.setMinimum(1)
self.spinbox_nbRandom.setMaximum(100)
self.spinbox_nbRandom.setSingleStep(1)
self.spinbox_nbRandom.setValue(1)
self.spinbox_nbRandom.hide()
self.label_nbRandom=QLabel('Number of random rectangles:')
h_boxnbRandom=QHBoxLayout()
h_boxnbRandom.addWidget(self.label_nbRandom)
h_boxnbRandom.addWidget(self.spinbox_nbRandom)
self.label_nbRandom.hide()
self.spinbox_nbRandom.hide()
img1 = cv2.imread(self.ImageNames[0])
self.spinbox_sizeRandomH = QSpinBox()
self.spinbox_sizeRandomH.setMinimum(1)
self.spinbox_sizeRandomH.setMaximum(len(img1))
self.spinbox_sizeRandomH.setSingleStep(5)
self.spinbox_sizeRandomH.setValue(10)
self.label_sizeRandomH=QLabel('Hight of the random rectangles:')
self.label_pixelsH=QLabel('pixels')
h_boxSizeRandomH=QHBoxLayout()
h_boxSizeRandomH.addWidget(self.label_sizeRandomH)
h_boxSizeRandomH.addWidget(self.spinbox_sizeRandomH)
h_boxSizeRandomH.addWidget(self.label_pixelsH)
self.label_sizeRandomH.hide()
self.spinbox_sizeRandomH.hide()
self.label_pixelsH.hide()
self.spinbox_sizeRandomW = QSpinBox()
self.spinbox_sizeRandomW.setMinimum(1)
self.spinbox_sizeRandomW.setMaximum(len(img1[0]))
self.spinbox_sizeRandomW.setSingleStep(5)
self.spinbox_sizeRandomW.setValue(10)
self.label_sizeRandomW=QLabel('Width of the random rectangles:')
self.label_pixelsW=QLabel('pixels')
h_boxSizeRandomW=QHBoxLayout()
h_boxSizeRandomW.addWidget(self.label_sizeRandomW)
h_boxSizeRandomW.addWidget(self.spinbox_sizeRandomW)
h_boxSizeRandomW.addWidget(self.label_pixelsW)
self.label_sizeRandomW.hide()
self.spinbox_sizeRandomW.hide()
self.label_pixelsW.hide()
self.CheckBox_Randomsize = QCheckBox('Choose a random size for the ROI')
self.CheckBox_Randomsize.setChecked(True)
self.CheckBox_Randomsize.hide()
self.CheckBox_RandomNumber = QCheckBox('Choose a random number of ROI')
self.CheckBox_RandomNumber.setChecked(True)
self.CheckBox_RandomNumber.hide()
self.button_OK=QPushButton('OK')
self.button_cancel=QPushButton('Cancel', default=False, autoDefault=False)
self.button_clear=QPushButton('Clear', default=False, autoDefault=False)
self.text_rectangle=QLabel()
self.CheckBox_SaveCroppedPictures = QCheckBox('Save the cropped pictures')
self.CheckBox_UseAsAMask = QCheckBox('Use the rectangle(s) as a mask')
self.CheckBox_UseAsAMask.setChecked(True)
self.button_NameROI=QPushButton('Name/View the areas', default=False, autoDefault=False)
#Create the layout
h_boxButton1=QHBoxLayout()
h_boxButton1.addWidget(self.button_cancel)
h_boxButton1.addWidget(self.button_OK)
v_boxCenter=QVBoxLayout()
v_boxCenter.addLayout(h_boxCenter)
v_boxCenter.addWidget(self.button_center)
v_boxRandom=QVBoxLayout()
v_boxRandom.addWidget(self.CheckBox_RandomNumber)
v_boxRandom.addLayout(h_boxnbRandom)
v_boxRandom.addWidget(self.CheckBox_Randomsize)
v_boxRandom.addLayout(h_boxSizeRandomH)
v_boxRandom.addLayout(h_boxSizeRandomW)
v_boxRandom.addWidget(self.button_random)
h_boxButton2=QHBoxLayout()
h_boxButton2.addWidget(self.button_start)
h_boxButton2.addLayout(v_boxCenter)
h_boxButton2.addLayout(v_boxRandom)
h_boxClear=QHBoxLayout()
h_boxClear.addWidget(self.button_clear)
h_boxClear.addWidget(self.button_NameROI)
h_boxCheckBox=QHBoxLayout()
h_boxCheckBox.addWidget(self.CheckBox_SaveCroppedPictures)
h_boxCheckBox.addWidget(self.CheckBox_UseAsAMask)
v_box=QVBoxLayout()
v_box.addWidget(self.label_Info)
v_box.addLayout(h_boxButton2)
v_box.addWidget(self.label_NbROI)
v_box.addWidget(self.text_rectangle)
v_box.addLayout(h_boxClear)
v_box.addLayout(h_boxCheckBox)
v_box.addLayout(h_boxButton1)
self.setLayout(v_box)
self.show()
#connect the buttons to their function
self.CheckBox_SaveCroppedPictures.clicked.connect(self.uncheckUseAsAMask)
self.CheckBox_UseAsAMask.clicked.connect(self.uncheckSaveCroppedPictures)
self.button_cancel.clicked.connect(self.cancel)
self.button_clear.clicked.connect(self.clear_text)
self.button_start.clicked.connect(self.SelectArea)
self.button_OK.clicked.connect(self.Validation)
self.button_NameROI.clicked.connect(self.NameArea)
self.button_center.clicked.connect(self.centerFunction)
self.button_random.clicked.connect(self.randomFunction)
self.CheckBox_Randomsize.clicked.connect(self.CheckRandomsizeFunction)
self.CheckBox_RandomNumber.clicked.connect(self.CheckRandomNumberFunction)
self.AreaNamesList=[]
self.coordinaterectangle=[]
def centerFunction(self):
""" This function is part of the class 'RegionOfInterestWindow'. \n
It is linked to the click of the button 'Use the center' (self.button_center) \n
This function calculates the coordinates of a rectangle in the center of the picture whose area is equal to a chosen pourcentage of the total area. """
self.coordinaterectangle=[]
self.spinbox_center.show()
self.label_center.show()
#Read the image and calculate the coordinates of a rectangle in the center.
img1 = cv2.imread(self.ImageNames[0])
a=((100-self.spinbox_center.value())/2)/100
x1=int(len(img1[0])*a)
y1=int(len(img1)*a)
x2=int(len(img1[0])*(1-a))
y2=int(len(img1)*(1-a))
self.coordinaterectangle=[[x1,y1,x2,y2]]
self.text_rectangle.setText(str(self.coordinaterectangle))
self.AreaNamesList=['Center'+str(self.spinbox_center.value())]
#Hide the not-needed widgets
self.label_sizeRandomW.hide()
self.spinbox_sizeRandomW.hide()
self.label_pixelsW.hide()
self.label_sizeRandomH.hide()
self.spinbox_sizeRandomH.hide()
self.label_pixelsH.hide()
self.label_nbRandom.hide()
self.spinbox_nbRandom.hide()
self.CheckBox_Randomsize.hide()
self.CheckBox_RandomNumber.hide()
self.CheckBox_RandomNumber.setChecked(True)
self.CheckBox_Randomsize.setChecked(True)
nbROI=1
self.label_NbROI.setText('Coordinates of the selected region: ('+str(nbROI)+' region)')
self.RefImg=self.ImageNames[0]
def randomFunction(self):
""" This function is part of the class 'RegionOfInterestWindow'. \n
It is linked to the click of the button 'Choose random rectangle' (self.button_random) \n
This function calculates random coordinates of a random or chosen number rectangle(s) with chosen or random dimensions """
self.coordinaterectangle=[]
self.CheckBox_RandomNumber.show()
self.CheckBox_Randomsize.show()
self.spinbox_center.hide()
self.label_center.hide()
img1 = cv2.imread(self.ImageNames[0])
if self.CheckBox_Randomsize.isChecked():
W=randint(1, len(img1[0])-1)
self.spinbox_sizeRandomW.setValue(W)
H=randint(1, len(img1)-1)
self.spinbox_sizeRandomH.setValue(H)
if self.CheckBox_RandomNumber.isChecked():
areaBox=self.spinbox_sizeRandomW.value()*self.spinbox_sizeRandomH.value()
areaImage=len(img1[0])*len(img1)
maxBox=int(areaImage/areaBox)
if maxBox>20:
n=randint(0, 20)
else:
n=randint(0, maxBox)
self.spinbox_nbRandom.setValue(n)
H=self.spinbox_sizeRandomH.value()
W=self.spinbox_sizeRandomW.value()
n=self.spinbox_nbRandom.value()
for i in range(n):
x=randint(0, len(img1[0]))
y=randint(0, len(img1))
x1=int(x-(W/2))
y1=int(y-(H/2))
x2=int(x+(W/2))
y2=int(y+(H/2))
if x1<=0:
x1=int(1)
x2=x1+int(W)
if y1<=0:
y1=int(1)
y2=y1+int(H)
if x2>=len(img1[0]):
x2=int(len(img1[0])-1)
x1=int(x2-W)
if y2>=len(img1):
y2=int(len(img1)-1)
y1=int(y2-H)
self.coordinaterectangle.append([x1,y1,x2,y2])
if len(self.coordinaterectangle)>5:
a=0
string=''
for i in range(int(len(self.coordinaterectangle)/5)):
string=string+str(self.coordinaterectangle[a:a+5])+'\n'
a=a+5
self.text_rectangle.setText(string)
else:
self.text_rectangle.setText(str(self.coordinaterectangle))
self.AreaNamesList=[]
for i in range(len(self.coordinaterectangle)):
self.AreaNamesList.append('Area_'+str(i+1))
nbROI=len(self.coordinaterectangle)
if nbROI==0 or nbROI==1:
self.label_NbROI.setText('Coordinates of the selected region: ('+str(nbROI)+' region)')
else:
self.label_NbROI.setText('Coordinates of the selected region: ('+str(nbROI)+' regions)')
self.RefImg=self.ImageNames[0]
def CheckRandomsizeFunction(self):
""" This function is part of the class 'RegionOfInterestWindow'. \n
It is linked to the click of the check box 'Choose a random size for the ROI' (self.CheckBox_Randomsize) \n
This function make other widgets appear or disappear """
if self.CheckBox_Randomsize.isChecked():
self.label_sizeRandomH.hide()
self.spinbox_sizeRandomH.hide()
self.label_pixelsH.hide()
self.label_sizeRandomW.hide()
self.spinbox_sizeRandomW.hide()
self.label_pixelsW.hide()
else:
self.label_sizeRandomH.show()
self.spinbox_sizeRandomH.show()
self.label_pixelsH.show()
self.label_sizeRandomW.show()
self.spinbox_sizeRandomW.show()
self.label_pixelsW.show()
def CheckRandomNumberFunction(self):
""" This function is part of the class 'RegionOfInterestWindow'. \n
It is linked to the click of the check box 'Choose a random number of ROI' (self.CheckBox_RandomNumber) \n
This function make other widgets appear or disappear """
if self.CheckBox_RandomNumber.isChecked():
self.label_nbRandom.hide()
self.spinbox_nbRandom.hide()
else:
self.label_nbRandom.show()
self.spinbox_nbRandom.show()
def uncheckSaveCroppedPictures(self):
""" This function is part of the class 'RegionOfInterestWindow'. \n
It is linked to the click of the check box 'Use the rectangle(s) as a mask' (self.CheckBox_UseAsAMask) \n
Make sure that self.CheckBox_UseAsAMask and self.CheckBox_SaveCroppedPictures are not checked at the same time """
self.CheckBox_SaveCroppedPictures.setChecked(False)
def uncheckUseAsAMask(self):
""" This function is part of the class 'RegionOfInterestWindow'. \n
It is linked to the click of the check box 'Save the cropped pictures' (self.CheckBox_SaveCroppedPictures) \n
Make sure that self.CheckBox_UseAsAMask and self.CheckBox_SaveCroppedPictures are not checked at the same time """
self.CheckBox_UseAsAMask.setChecked(False)
def clear_text(self):
""" This function is part of the class 'RegionOfInterestWindow'. \n
It is linked to the click of the check box 'Clear' (self.button_clear) \n
Clear the list of coordinates """
self.text_rectangle.clear()
def cancel(self):
""" This function is part of the class 'RegionOfInterestWindow'. \n
It is linked to the click of the check box 'Cancel' (self.button_cancel) \n
Close the window without saving any coordinates """
self.text_rectangle.setText('')
self.coordinaterectangle=[]
self.hide()
def SelectArea(self):
""" This function is part of the class 'RegionOfInterestWindow'. \n
It is linked to the click of the button 'Select the area(s)' (self.button_start) \n
Open the SelectAreaWindow """
#Hide the not-needed widgets
self.label_sizeRandomW.hide()
self.spinbox_sizeRandomW.hide()
self.label_pixelsW.hide()
self.label_sizeRandomH.hide()
self.spinbox_sizeRandomH.hide()
self.label_pixelsH.hide()
self.label_nbRandom.hide()
self.spinbox_nbRandom.hide()
self.CheckBox_Randomsize.hide()
self.CheckBox_RandomNumber.hide()
self.CheckBox_RandomNumber.setChecked(True)
self.CheckBox_Randomsize.setChecked(True)
self.spinbox_center.hide()
self.label_center.hide()