-
Notifications
You must be signed in to change notification settings - Fork 0
/
BAS.py
1383 lines (1120 loc) · 57.7 KB
/
BAS.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 matplotlib
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import os
import cv2
import numpy as np
from datetime import date
from PIL import Image, ImageQt
import pandas as pd
import matplotlib.ticker as mtick
from scipy.stats import kurtosis, skew
from PyQt5 import QtCore, QtGui, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT as NavigationToolbar
matplotlib.use('Qt5Agg')
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
plt.style.use('ggplot')
class InitialWindow(QtWidgets.QMainWindow):
signal = QtCore.pyqtSignal(str)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
location = os.path.dirname(os.path.realpath(__file__))
self.selected_file = None
myQWidget = QtWidgets.QWidget()
self.pix_map = QtGui.QPixmap(os.path.join(location, 'welcome_log2.jpeg'))
self.image_label = QtWidgets.QLabel("")
self.image_label.setPixmap(self.pix_map)
self.image_label.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
self.app_label = QtWidgets.QLabel("B.A.S")
self.app_label.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
self.app_label.setFont(QtGui.QFont('Arial', 64, QtGui.QFont.Bold))
self.new_button = QtWidgets.QPushButton("Start new csv file")
self.new_button.setToolTip('Select a directory where to position the results.')
self.load_button = QtWidgets.QPushButton("Load csv file")
self.load_button.setToolTip("Select a previously generated csv file to continue modifying it.")
root_layout = QtWidgets.QVBoxLayout()
second_row = QtWidgets.QHBoxLayout()
new_layout = QtWidgets.QHBoxLayout()
load_layout = QtWidgets.QHBoxLayout()
myQWidget.setLayout(root_layout)
self.setCentralWidget(myQWidget)
new_layout.addWidget(self.new_button)
load_layout.addWidget(self.load_button)
second_row.addLayout(new_layout)
second_row.addLayout(load_layout)
root_layout.addWidget(self.image_label, stretch = 2)
root_layout.addWidget(self.app_label, stretch = 1)
root_layout.addLayout(second_row, stretch = 4)
self.new_button.clicked.connect(self.create_file)
self.load_button.clicked.connect(self.choose_file)
self.setFixedWidth(900)
self.setFixedHeight(760)
self.setWindowIcon(QtGui.QIcon(os.path.join(location, 'welcome_log2.png')))
self.setWindowTitle('Biofilm Analysis Software')
def create_file(self):
file_path = ''
file_dialog = QtWidgets.QFileDialog(self)
file_dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave)
file_dialog.setNameFilter("CSV files (*.csv)")
file_dialog.setDefaultSuffix("csv")
file_dialog.setViewMode(QtWidgets.QFileDialog.Detail)
if file_dialog.exec_():
file_path = file_dialog.selectedFiles()[0]
with open(file_path, 'w', newline='') as csvfile:
# You can write header if needed
# csv_writer = csv.writer(csvfile)
# csv_writer.writerow(['Column1', 'Column2', 'Column3'])
pass
#print(f"CSV file created: {file_path}")
if file_path!='':
self.selected_file = file_path
self.signal.emit('Open SecondWindow')
self.close()
def choose_file(self):
file, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Select a file',
os.path.dirname(os.path.abspath(__file__)),
"Comma-separated values (*.csv)")
if file !='':
self.selected_file = file
self.signal.emit('Open SecondWindow')
self.close()
class ScreenHandler(QtWidgets.QMainWindow):
'''
Class that handles interaction in between screens, sending signals according to the interaction
the user had with the GUI.
'''
def __init__(self):
super().__init__()
self.first_window = InitialWindow()
self.second_window = None
self.first_window.signal.connect(self.change_window)
self.first_window.show()
@QtCore.pyqtSlot(str)
def change_window(self, event):
'''
Function to differentiate each possible case the user can have when interacting with the
program.
'''
if event == 'Open SecondWindow':
self.second_window = MainWindow(self.first_window.selected_file) #add the selected file
self.second_window.signal.connect(self.change_window)
self.second_window.setStyleSheet("QMainWindow { border: 1px solid black; }")
self.second_window.show()
elif event == 'Change SecondWindow file':
new_file = self.second_window.new_file
self.second_window = MainWindow(new_file)
self.second_window.setStyleSheet("QMainWindow { border: 1px solid black; }")
self.second_window.show()
class ROIWindow(QtWidgets.QMainWindow):
window_closed = QtCore.pyqtSignal()
coordinates_changed = QtCore.pyqtSignal(QtCore.QRect, bool, int)
def __init__(self, image_path: str, crosshair_flag: bool, window_title: str, idd: int):
super().__init__()
self.setWindowTitle(window_title)
self.img_path = image_path
self.mouse_position = QtCore.QPoint(0, 0)
self.start_point = QtCore.QPoint(0, 0)
self.end_point = QtCore.QPoint(0, 0)
self.drawing_square = False
self.last_rectangle = None
self.draw_crosshair = crosshair_flag
self.idd = idd
self.normal_pen = QtGui.QPen(QtCore.Qt.blue, 2, QtCore.Qt.SolidLine)
self.dashed_pen = QtGui.QPen(QtCore.Qt.red, 2, QtCore.Qt.DashLine)
self.setMouseTracking(True)
location = os.path.dirname(os.path.realpath(__file__))
self.setWindowIcon(QtGui.QIcon(os.path.join(location, 'welcome_log2.png')))
img = QtGui.QImage(self.img_path)
width = img.width()
height= img.height()
print('Image dimensions(H,W):', (height,width))
self.setGeometry(100, 100, width, height)
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
# Draw background image
background_image = QtGui.QPixmap(self.img_path)
painter.drawPixmap(0, 0, self.width(), self.height(), background_image)
# Draw vertical line
painter.setPen(self.dashed_pen)
painter.drawLine(self.mouse_position.x(), 0, self.mouse_position.x(), self.height())
# Draw horizontal line
painter.drawLine(0, self.mouse_position.y(), self.width(), self.mouse_position.y())
if self.last_rectangle:
painter.setPen(self.normal_pen)
painter.drawRect(self.last_rectangle)
if self.draw_crosshair:
# Draw crosshair
center_x = (self.start_point.x() + self.end_point.x()) // 2
center_y = (self.start_point.y() + self.end_point.y()) // 2
painter.drawLine(center_x, self.start_point.y(), center_x, self.end_point.y())
painter.drawLine(self.start_point.x(), center_y, self.end_point.x(), center_y)
# Draw square
if self.drawing_square:
painter.setPen(self.normal_pen)
square_rect = QtCore.QRect(self.start_point, self.end_point)
painter.drawRect(square_rect)
if self.draw_crosshair:
# Draw crosshair
center_x = (self.start_point.x() + self.end_point.x()) // 2
center_y = (self.start_point.y() + self.end_point.y()) // 2
painter.drawLine(center_x, self.start_point.y(), center_x, self.end_point.y())
painter.drawLine(self.start_point.x(), center_y, self.end_point.x(), center_y)
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self.start_point = event.pos()
self.end_point = event.pos()
self.last_rectangle = None
self.drawing_square = True
self.update()
def mouseMoveEvent(self, event):
self.mouse_position = event.pos()
if self.drawing_square:
self.end_point = event.pos()
self.update()
def mouseReleaseEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self.end_point = event.pos()
self.drawing_square = False
self.last_rectangle = QtCore.QRect(self.start_point, self.end_point)
self.update()
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Return or event.key() == QtCore.Qt.Key_Enter:
#if self.last_rectangle:
# print('Top-left coordinates:', self.last_rectangle.topLeft())
# print("Bottom-right coordinates:", (self.last_rectangle.x()+self.last_rectangle.width(), self.last_rectangle.y()+self.last_rectangle.height()))
if self.last_rectangle is not None:
self.coordinates_changed.emit(self.last_rectangle, self.draw_crosshair, self.idd)
self.close()
def closeEvent(self, event):
self.window_closed.emit()
event.accept()
def nothing(x):
pass
def manual_thresh(image: np.ndarray) -> int:
'''
Function to create the window for the manual thresh selection
This window shows the image histogram with a trackbar and an input.
This trackbar has a range of 256 values (0 -255), as the images
contain 8-bit information.
A vertical line is drawn in the figure, and it represents the value
of the manual threshold.
Once the value is selected, this function return the threshold to the
main window.
'''
thresh=0
cv2.namedWindow("Trackbar")
cv2.resizeWindow("Trackbar", 240,240)
cv2.createTrackbar('Threshold','Trackbar',0,255, nothing)
cv2.setTrackbarPos('SMax', 'Manual segmentation', 120)
plt.hist(image.ravel(), 256, [0,256])
plt.axvline(thresh, color = 'k', linestyle= 'dashed', linewidth=1)
plt.show()
thresh = cv2.getTrackbarPos('Threshold','Trackbar')
cv2.destroyAllWindows()
return thresh
class MplCanvas(FigureCanvasQTAgg):
#MplCanvas is a class that contains all the attributes related to the
#canvas drawn in the main UI.
def __init__(self, parent=None, width=12, height=9, dpi=100, axes=1):
'''
During the initilization of the class, a figure with 3 axes is
created. This can be modified in other versions.
'''
self.fig = Figure(figsize=(width, height), dpi=dpi)
self.ax1= None
self.ax2= None
self.ax3= None
super().__init__(self.fig)
class SliderWindow(QtWidgets.QMainWindow):
#SliderWindow is a class that containts all the attributes related to the
#window created during the threshold selection. This window contains
#a canvas, an slider and an input box.
def __init__(self, image: np.ndarray, color: str, *args, **kwargs):
'''
During the initilization, this class creates all the necessary attributes
and acommodates the layout to show all the information in order.
'''
super().__init__(*args, **kwargs)
self.image = image
self.label = QtWidgets.QLabel()
self.button = QtWidgets.QPushButton("Confirm Threshold")
self.recommended_label = QtWidgets.QLabel("Recommended Thresh: " + str(np.floor(np.percentile(self.image[self.image>0],0.05))))
#self.recommended_label.setAlignment(QtCore.AlignHCenter)
self.layout = QtWidgets.QVBoxLayout()
self.top_layout = QtWidgets.QHBoxLayout()
self.slider = QtWidgets.QSlider()
self.slider.setGeometry(QtCore.QRect(150,100,150,15))
self.slider.setOrientation(QtCore.Qt.Horizontal)
self.slider.setMinimum(0)
self.slider.setMaximum(255)
self.slider.setSingleStep(1)
self.user_input = QtWidgets.QLineEdit("", self)
self.enter = QtWidgets.QPushButton("Draw Line")
self.onlyInt = QtGui.QIntValidator(0,255, self)
self.user_input.setValidator(self.onlyInt)
self.canvas = MplCanvas(self, dpi=100)
self.slider_value = None
self.color = color
self.middle_layout = QtWidgets.QHBoxLayout()
self.middle_layout.addWidget(self.recommended_label)
self.middle_layout.setAlignment(QtCore.Qt.AlignCenter)
#self.middle_layout.addStretch()
self.top_layout.addStretch(3)
self.top_layout.addWidget(self.label)
self.top_layout.addStretch(3)
self.top_layout.addWidget(self.user_input)
self.top_layout.addWidget(self.enter)
self.top_layout.addWidget(self.button)
self.layout.addLayout(self.top_layout)
self.layout.addWidget(self.slider)
self.layout.addStretch()
self.layout.addLayout(self.middle_layout)
self.layout.addStretch()
self.layout.addWidget(self.canvas)
self.layout.setAlignment(QtCore.Qt.AlignHCenter)
self.widget = QtWidgets.QWidget()
self.widget.setLayout(self.layout)
self.setCentralWidget(self.widget)
self.slider.valueChanged.connect(self.set_line)
self.button.clicked.connect(self.set_thresh)
self.enter.clicked.connect(lambda ch, p=0: self.draw_line(p))
self.user_input.returnPressed.connect(self.on_space_pressed)
#self.user_input.returnPressed.connect(lambda:self.draw_line2())
self.setWindowTitle("Select Threshold")
self.show_histogram()
self.show()
def on_space_pressed(self):
thresh = int(self.user_input.text())
img = np.array(self.image)
self.canvas.fig.clf()
self.canvas.ax1 = self.canvas.fig.add_subplot(111)
vals, bins, _ = self.canvas.ax1.hist(img.flatten(),256, [1,255])
self.canvas.ax1.axvline(thresh, color = 'k', linestyle= 'dashed', linewidth=1)
self.canvas.draw()
self.slider.setSliderPosition(thresh)
#self.draw_line(0)
def show_histogram(self):
'''
This function draws the image histogram in the canvas that is showed in the
window.
'''
img = np.array(self.image)
self.canvas.fig.clf()
self.canvas.ax1 = self.canvas.fig.add_subplot(111)
self.canvas.ax1.set_title('Histogram for ' +self.color+' Channel for Reference Image')
self.canvas.ax1.set_xlabel('Pixel Value')
self.canvas.ax1.set_ylabel('Frequency [N]')
vals, bins, _ = self.canvas.ax1.hist(img.flatten(),256, [1,255])
self.canvas.draw()
def set_line(self):
'''
This function draws a vertical line that represents tha selected value
with the slider.
'''
self.label.setText("Threshold: " + str(self.slider.value()))
self.canvas.fig.clf()
self.show_histogram()
self.canvas.ax1.axvline(int(self.slider.value()), color = 'k', linestyle= 'dashed', linewidth=1)
self.canvas.draw()
def draw_line(self, idx: int):
'''
This function draws a vertical line when the user uses the input box
is an alternative way of showing the threshold.
'''
try:
print(idx)
value = int(self.user_input.text())
print(value)
img = np.array(self.image)
self.canvas.fig.clf()
self.canvas.ax1 = self.canvas.fig.add_subplot(111)
vals, bins, _ = self.canvas.ax1.hist(img.flatten(),256, [1,255])
self.canvas.ax1.axvline(value, color = 'k', linestyle= 'dashed', linewidth=1)
self.canvas.draw()
self.slider.setSliderPosition(value)
except:
pass
def set_thresh(self) -> int:
'''
This function closes the slider window once the user has chosen the
threshold.
It returns the value to the main window
'''
self.slider_value = int(self.slider.value())
self.close()
return self.slider.value()
class TableWindow(QtWidgets.QMainWindow):
def __init__(self, dataframe: pd.DataFrame, *args, **kwargs):
super().__init__(*args, **kwargs)
self.widget = QtWidgets.QWidget()
self.scroll = QtWidgets.QScrollArea()
self.layout = QtWidgets.QVBoxLayout()
self.datatable = QtWidgets.QTableWidget()
self.df = dataframe
self.datatable.setColumnCount(self.df.shape[1])
self.datatable.setRowCount(self.df.shape[0])
self.datatable.setHorizontalHeaderLabels(self.df.columns)
#self.datatable.horizontalHeaderItem().setTextAlignment(Qt.AlignHCenter)
for i in range(self.df.shape[0]):
for j in range(self.df.shape[1]):
self.datatable.setItem(i,j,QtWidgets.QTableWidgetItem(str(self.df.iloc[i, j])))
self.scroll.setWidget(self.datatable)
self.layout.addWidget(self.datatable)
self.widget.setLayout(self.layout)
self.setCentralWidget(self.widget)
self.setWindowTitle("Result Dataframe")
self.show()
class WelcomeDialog(QtWidgets.QDialog):
def __init__(self, parent = None, *args, **kwargs):
super().__init__(parent)
location = os.path.dirname(os.path.realpath(__file__))
self.setWindowIcon(QtGui.QIcon(os.path.join(location, 'welcome_log2.png')))
self.setWindowTitle('Welcome')
# Add the logo to the message box
logo_label = QtWidgets.QLabel()
logo_pixmap = QtGui.QPixmap(os.path.join(location, 'welcome_log2.png')) # Replace "path/to/your/logo.png" with the actual path to your logo
logo_label.setPixmap(logo_pixmap)
logo_label.setAlignment(QtCore.Qt.AlignCenter)
# Add welcome message to the layout
welcome_label = QtWidgets.QLabel(self)
welcome_label.setText("Welcome to BAS!")
welcome_label.setAlignment(QtCore.Qt.AlignCenter)
# Add instructions to the layout
instructions_label = QtWidgets.QLabel(self)
instructions_label.setText('Here are some brief instructions to get you started:\n1.'+
'Select the reference/blank well.\n2. Select the growth well.\n3.'+
'Select the geometry of the Region of Interest (ROI).\n4.'+
'Apply a manual crop to the ROI of each image.\n5. Select the color transformation option.\n6.'+
'Define the threshold value according to the blank histogram.\n7.'+
'Apply the manual thresholding.\n8. Obtain the results. \n9. Add the results to the csv file if satisfactory.')
instructions_label.setAlignment(QtCore.Qt.AlignCenter)
#'<a href="https://github.com/your_username/your_repository">Click here to visit the GitHub repository</a>'
#Add link to the Github repo
link_label = QtWidgets.QLabel()
link_label.setText('For more information and detailed usage examples, please visit our '+
'<a href="https://github.com/Biofilm-Project/BAS">GitHub repository</a>.')
link_label.setAlignment(QtCore.Qt.AlignCenter)
link_label.setOpenExternalLinks(True)
link_label.setTextInteractionFlags(QtCore.Qt.TextBrowserInteraction)
#self.info_box.addWidget(QtWidgets.QMessageBox.Ok)
message_layout = QtWidgets.QVBoxLayout()
message_layout.addWidget(logo_label)
message_layout.addWidget(welcome_label)
message_layout.addWidget(instructions_label)
message_layout.addWidget(link_label)
#message_layout.addWidget(QtWidgets.QMessageBox.Ok)
self.setLayout(message_layout)
class MainWindow(QtWidgets.QMainWindow):
signal = QtCore.pyqtSignal(str)
def __init__(self, filename: str, *args, **kwargs):
super().__init__(*args, **kwargs)
#Getting screen dimensions
screen = QtWidgets.QDesktopWidget().screenGeometry()
self.screen_width = screen.width()
self.screen_height= screen.height()
#Setting up font size
font = QtGui.QFont()
font.setPointSize(10)
#Getting executable/main.py file location
location = os.path.dirname(os.path.realpath(__file__))
self.location = location.replace("\\","//") +"//"
self.menubar = self.menuBar()
self.file_menu = self.menubar.addMenu('File')
self.data_menu = self.menubar.addMenu('Data')
self.help_menu = self.menubar.addMenu('Help')
self.open_action = QtWidgets.QAction('Open csv file', self)
self.file_menu.addAction(self.open_action)
self.open_action.triggered.connect(self.open_file)
self.showData_action = QtWidgets.QAction('Show Data', self)
self.showData_action.triggered.connect(self.show_dataframe)
self.data_menu.addAction(self.showData_action)
self.getHelp_action = QtWidgets.QAction('Show B.A.S Instructions')
self.help_menu.addAction(self.getHelp_action)
self.getHelp_action.triggered.connect(self.open_HelpDialog)
#Settin up widgets --- Main UI
self.choose_file = QtWidgets.QLabel("Choose Folder")
self.choose_file.setFont(font)
self.next_button = QtWidgets.QPushButton()
self.previous_button = QtWidgets.QPushButton()
self.next_button2 = QtWidgets.QPushButton()
self.previous_button2 = QtWidgets.QPushButton()
left_icon = QtGui.QIcon(self.location +"left-arrow.png")
right_icon = QtGui.QIcon(self.location +"right-arrow.png")
self.next_button.setIcon(right_icon)
self.next_button2.setIcon(right_icon)
self.previous_button.setIcon(left_icon)
self.previous_button2.setIcon(left_icon)
self.current_folder = 0
self.ref_index = 0
self.bio_index = 0
self.filename_label = QtWidgets.QLabel("")
self.filename_label.setFont(font)
self.filename_label2 = QtWidgets.QLabel("")
self.filename_label2.setFont(font)
self.choose_button = QtWidgets.QPushButton("...")
self.ready_button = QtWidgets.QPushButton("Ready")
self.ready_button.setFont(font)
self.next_folder = QtWidgets.QPushButton('Next Folder')
self.previous_folder = QtWidgets.QPushButton('Prev Folder')
self.clear_button = QtWidgets.QPushButton("Clear")
self.clear_button.setFont(font)
self.first_step = QtWidgets.QLabel("Choose Work Space")
self.first_step.setFont(font)
self.first_step.setStyleSheet("background-color: lightgreen; border: 1px solid black")
self.second_step = QtWidgets.QLabel("Manual Cropping")
self.second_step.setFont(font)
self.second_step.setStyleSheet("border: 1px solid black")
self.third_step = QtWidgets.QLabel("Select Color Scale")
self.third_step.setFont(font)
self.third_step.setStyleSheet("border: 1px solid black ")
self.fourth_step = QtWidgets.QLabel("Select Threshold")
self.fourth_step.setFont(font)
self.fourth_step.setStyleSheet("border: 1px solid black")
self.fifth_step = QtWidgets.QLabel("Output")
self.fifth_step.setFont(font)
self.fifth_step.setStyleSheet("border: 1px solid black")
self.new_ref_button = QtWidgets.QPushButton('Crop New Reference ROI')
self.new_ref_button.setFont(font)
self.new_growth_button = QtWidgets.QPushButton('Crop New Growth ROI')
self.new_growth_button.setFont(font)
self.ROI_button = QtWidgets.QPushButton("Crop Region of Interest")
self.ROI_button.setFont(font)
self.auto_crop = QtWidgets.QPushButton('Automatic ROI Crop')
self.auto_crop.setFont(font)
self.geometry_groupbox = QtWidgets.QGroupBox('Cropping Geometry Options')
self.square_radio = QtWidgets.QRadioButton("Square ROI")
self.square_radio.setFont(font)
self.square_radio.setChecked(False)
self.circular_radio = QtWidgets.QRadioButton("Circular ROI")
self.circular_radio.setFont(font)
self.circular_radio.setChecked(False)
self.shape_box = QtWidgets.QHBoxLayout()
self.shape_box.addWidget(self.circular_radio)
self.shape_box.addWidget(self.square_radio)
self.geometry_groupbox.setLayout(self.shape_box)
self.geometry_groupbox.setEnabled(False)
self.color_groupbox = QtWidgets.QGroupBox('Color Transformation Options')
self.radio_green = QtWidgets.QRadioButton("Green")
self.radio_green.setFont(font)
self.radio_green.setChecked(False)
self.radio_gray = QtWidgets.QRadioButton("Gray")
self.radio_gray.setFont(font)
self.radio_green.setChecked(False)
self.color_box = QtWidgets.QHBoxLayout()
self.color_box.addWidget(self.radio_green)
self.color_box.addWidget(self.radio_gray)
self.color_groupbox.setLayout(self.color_box)
self.color_groupbox.setEnabled(False)
self.next_step = QtWidgets.QPushButton("Confirm Color Scale")
self.next_step.setFont(font)
self.thresh_button = QtWidgets.QPushButton("Set Threshold")
self.thresh_button.setFont(font)
self.remove_button = QtWidgets.QPushButton('Apply Threshold')
self.remove_button.setFont(font)
self.add_button = QtWidgets.QPushButton("Add Result")
self.add_button.setFont(font)
self.state_label = QtWidgets.QLabel("... on file '___result.csv - currently 0 rows")
self.state_label.setFont(font)
self.initial_round = True
self.b_files = None
self.c_files = None
self.folders = None
self.image = None
self.image2 = None
self.roi_window = None
self.roi_window2= None
self.roi = None
self.roi2 = None
self.pix_map = None
self.pix_map2 = None
self.roi_map = None
self.roi_map2 = None
self.conv_img = None
self.conv_img2 = None
self.conv_map = None
self.conv_map2 = None
self.directory = None
self.just_b_filename = None
self.just_c_filename = None
self.contador_ref = 0
self.color_selection = None
self.threshold = None
self.image_color = None
self.image_color2 = None
self.fig = None
self.ax = None
self.ax2 = None
self.slider_window = None
self.table_window = None
self.result_canvas = None
self.toolbar = None
self.export_name = filename
self.new_file = None
self.previous_file_flag = False
if os.stat(self.export_name).st_size>0:
#print('File with data')
self.df = pd.read_csv(self.export_name)
self.previous_file_flag=True
else:
#print('New file')
self.df = None
self.previous_file_flag = False
self.welcome_dialog = None
self.export_list = list()
self.temp = list()
self.image_label = QtWidgets.QLabel()
self.image_label2 = QtWidgets.QLabel()
self.image_label3 = QtWidgets.QLabel()
self.image_label4 = QtWidgets.QLabel()
self.image_label5 = QtWidgets.QLabel()
self.image_label6 = QtWidgets.QLabel()
self.moving_box = QtWidgets.QHBoxLayout()
self.moving_box2 = QtWidgets.QHBoxLayout()
self.moving_box.addWidget(self.previous_button)
self.moving_box.addWidget(self.next_button)
self.moving_box2.addWidget(self.previous_button2)
self.moving_box2.addWidget(self.next_button2)
self.next_button.setHidden(True)
self.next_button2.setHidden(True)
self.previous_button.setHidden(True)
self.previous_button2.setHidden(True)
self.choose_box = QtWidgets.QHBoxLayout()
self.choose_box.addWidget(self.choose_file)
self.choose_box.addWidget(self.choose_button)
self.choose_box.addStretch()
self.previous_folder.setEnabled(False)
self.next_folder.setEnabled(False)
self.top_box = QtWidgets.QHBoxLayout()#Tree
self.first_box = QtWidgets.QVBoxLayout()
self.second_box = QtWidgets.QVBoxLayout()
self.third_box = QtWidgets.QVBoxLayout()
self.fourth_box = QtWidgets.QVBoxLayout()
self.fifth_box = QtWidgets.QVBoxLayout()
self.right_box = QtWidgets.QVBoxLayout()
self.second_right_box = QtWidgets.QVBoxLayout()
self.right_box.addWidget(self.image_label)
self.right_box.addWidget(self.filename_label)
self.right_box.addLayout(self.moving_box)
self.right_box.addStretch()
self.second_right_box.addWidget(self.image_label2)
self.second_right_box.addWidget(self.filename_label2)
self.second_right_box.addLayout(self.moving_box2)
self.second_right_box.addStretch()
self.first_box.addWidget(self.first_step)
self.first_box.addLayout(self.choose_box)
self.first_box.addLayout(self.right_box)
self.first_box.addLayout(self.second_right_box)
self.second_box.addWidget(self.second_step)
self.second_box.addWidget(self.geometry_groupbox)
self.second_box.addWidget(self.ROI_button)
self.second_box.addWidget(self.image_label3)
self.second_box.addWidget(self.new_ref_button)
self.second_box.addWidget(self.image_label4)
self.second_box.addWidget(self.new_growth_button)
self.second_box.addStretch()
self.ROI_button.setEnabled(False)
self.new_ref_button.setVisible(False)
self.new_growth_button.setVisible(False)
self.third_box.addWidget(self.third_step)
self.third_box.addWidget(self.color_groupbox)
self.third_box.addWidget(self.image_label5)
self.third_box.addWidget(self.image_label6)
self.third_box.addWidget(self.next_step)
self.third_box.addStretch()
self.next_step.setEnabled(False)
self.fourth_box.addWidget(self.fourth_step)
self.fourth_box.addWidget(self.thresh_button)
self.fourth_box.addWidget(self.remove_button)
self.fourth_box.addStretch()
self.thresh_button.setEnabled(False)
self.remove_button.setEnabled(False)
self.results_row = QtWidgets.QHBoxLayout()
self.results_row.addWidget(self.add_button)
self.results_row.addWidget(self.state_label)
self.state_label.setVisible(False)
self.results_row.addStretch()
self.fifth_box.addWidget(self.fifth_step)
self.fifth_box.addLayout(self.results_row)
self.add_button.setEnabled(False)
self.fifth_box.addStretch()
self.top_box.addLayout(self.first_box)
self.top_box.addLayout(self.second_box)
self.top_box.addLayout(self.third_box)
self.top_box.addLayout(self.fourth_box)
self.top_box.addLayout(self.fifth_box)
self.choose_button.clicked.connect(self.get_image)
self.ROI_button.clicked.connect(lambda ch, p=0: self.select_roi(p))
self.new_ref_button.clicked.connect(lambda ch, p=1: self.select_roi(p))
self.new_growth_button.clicked.connect(lambda ch, p=2: self.select_roi(p))
self.next_step.clicked.connect(self.selecting_color)
self.thresh_button.clicked.connect(self.thresholding)
self.previous_button.clicked.connect(self.previous_ref)
self.next_button.clicked.connect(self.next_ref)
self.previous_button2.clicked.connect(self.previous_bio)
self.next_button2.clicked.connect(self.next_bio)
self.radio_green.clicked.connect(self.show_scale)
self.radio_gray.clicked.connect(self.show_scale)
self.remove_button.clicked.connect(self.execute_thresh)
self.add_button.clicked.connect(self.add_result)
self.layout = QtWidgets.QVBoxLayout()
self.layout.addLayout(self.top_box)
self.widget = QtWidgets.QWidget()
self.widget.setLayout(self.layout)
self.setCentralWidget(self.widget)
self.setWindowIcon(QtGui.QIcon(os.path.join(location, 'welcome_log2.png')))
self.setWindowTitle('Biofilm Analysis Software')
self.show()
self.centerWindow()
def open_file(self):
file, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Select a file",
os.path.dirname(os.path.abspath(__file__)),
"Comma-separated values (*.csv)")
if file !='':
self.new_file = file
self.signal.emit('Change SecondWindow file')
self.close()
def open_HelpDialog(self):
self.welcome_dialog = WelcomeDialog()
self.welcome_dialog.exec_()
def get_image(self):
'''
Initial function in the Main UI that allows the user to choose a particular directory/folder for further analysis.
During this function, multiple attributes are filled, such as the directory and all the filenames inside it.
Also, shows the first images (reference and biofilm) following an alphabetical order.
If the user chooses an empty directory or something alike, there'll be an error dialog with a set of instructions.
'''
self.ref_index = 0
self.bio_index = 0
directory = QtWidgets.QFileDialog.getExistingDirectory(self, "Select a folder", os.path.dirname(os.path.abspath(__file__)))
if not directory=='':
directory = directory.replace("/","//")
self.directory = directory
self.folders = [self.directory+'//'+folder for folder in os.listdir(self.directory) if folder[-4:]!='.txt']
if len(self.folders) == 0:
error_dialog = QtWidgets.QErrorMessage()
error_dialog.showMessage("Choose a folder with the correct distribution:"+"\n"+" 1) Biofilm 2) Reference")
error_dialog.setWindowTitle("Error Message")
error_dialog.exec_()
else:
self.b_files = [self.directory+'//'+file for file in os.listdir(self.directory)]
self.c_files = [self.directory+'//'+file for file in os.listdir(self.directory)]
self.just_b_filename = [file for file in os.listdir(self.directory)]
self.just_c_filename = [file for file in os.listdir(self.directory)]
if(len(self.c_files)>0 and len(self.b_files)>0):
self.next_button.setHidden(False)
self.next_button2.setHidden(False)
self.previous_button.setHidden(False)
self.previous_button2.setHidden(False)
self.previous_button.setEnabled(False)
self.previous_button2.setEnabled(False)
self.filename_label.setText("Reference Well "+self.just_b_filename[self.ref_index].split('.')[0])
self.filename_label2.setText("Growth Well "+self.just_c_filename[self.bio_index].split('.')[0])
self.update_image_label(self.b_files[self.ref_index], True)
self.update_image_label(self.c_files[self.bio_index], False)
self.first_step.setStyleSheet("border: 1px solid black")
self.second_step.setStyleSheet("background-color: lightgreen; border: 1px solid black")
self.ROI_button.setEnabled(True)
self.previous_folder.setEnabled(True)
self.next_folder.setEnabled(True)
self.check_csv()
self.geometry_groupbox.setEnabled(True)
self.centerWindow()
def check_csv(self):
experimento= self.directory.split('//')[-1]
try:
self.df = pd.read_csv(self.export_name)
self.export_list = [self.df.loc[x,:].values.tolist() for x in range(0,self.df.shape[0])]
rows = self.df.shape[0]
print(self.df)
except:
self.export_list = list()
rows = 0
self.state_label.setVisible(True)
self.update_state_label(experimento, rows)
def update_state_label(self, exp: str, rows: int):
filename = self.export_name.split('/')[-1]
if rows>1:
end = 'rows'
else:
end = 'row'
self.state_label.setText('... on file '+filename + ' - currently '+str(rows)+end)
def show_roi_window(self, image_path: str, idd: int, crosshair_flag: bool, pair_flag: bool):#image,
'''
Function to perform the manual crop in the image.
This crop has a circular shape as the ROI has that shape.
You select the borders of the ROI, and this function
obtains the coordinates of the selected radius.
'''
if idd == 0:
self.roi_window = ROIWindow(image_path, crosshair_flag, "Reference Well", idd)
self.roi_window.coordinates_changed.connect(self.process_coordinates)
if pair_flag:
self.roi_window.window_closed.connect(self.show_next_roi_window)
self.roi_window.show()
else:
self.roi_window2 = ROIWindow(image_path, crosshair_flag, "Growth Well", idd)
self.roi_window2.coordinates_changed.connect(self.process_coordinates)
if pair_flag:
self.roi_window.window_closed.connect(self.show_next_roi_window)
self.roi_window2.show()
def show_next_roi_window(self):
self.show_roi_window(self.c_files[self.bio_index], 1, True, False)
def process_coordinates(self, rectangle: QtCore.QRect, circular_flag: bool, idd: int):
if rectangle is not None:
top_left = (rectangle.x(), rectangle.y())
bottom_right = (rectangle.x() + rectangle.width(), rectangle.y() + rectangle.height())
print('Top-left coordinates(X,Y):', top_left)
print('Bottom-right coordinates(X,Y):', bottom_right)
r = (rectangle.x(), rectangle.y(), rectangle.width(), rectangle.height())
if circular_flag:
if idd == 0:#ref
img = cv2.cvtColor(np.array(self.image), cv2.COLOR_RGB2BGR)
else:#bio
img = cv2.cvtColor(np.array(self.image2), cv2.COLOR_RGB2BGR)
just_roi = self.circular_crop(img, r)
else:
if idd == 0:
img = cv2.cvtColor(np.array(self.image), cv2.COLOR_RGB2BGR)
else:
img = cv2.cvtColor(np.array(self.image2), cv2.COLOR_RGB2BGR)
just_roi = self.square_crop(img, r)
roi_rgb = cv2.cvtColor(just_roi, cv2.COLOR_BGR2RGB)
self.update_one_ROI(idd+1, roi_rgb)
self.centerWindow()
def circular_crop(self, img: np.ndarray, r: tuple[int, int, int, int]) -> np.ndarray:
cropped = img[int(r[1]):int(r[1]+r[3]), int(r[0]):int(r[0]+r[2])]
mask = np.zeros((cropped.shape[0],cropped.shape[1]), dtype = np.uint8)
shapes = cropped.shape
center = (shapes[1]//2 , shapes[0]//2)
rad = max(center)
blank_circle = cv2.circle(mask, center, rad, (255,0,0), -1)
result = cv2.bitwise_and(cropped, cropped, mask= mask)
return result
def square_crop(self, img: np.ndarray, r: tuple[int, int, int, int]) -> np.ndarray:
cropped = img[int(r[1]):int(r[1]+r[3]), int(r[0]):int(r[0]+r[2])]
mask = np.ones((cropped.shape[0],cropped.shape[1]), dtype = np.uint8)
shapes = cropped.shape
result = cv2.bitwise_and(cropped, cropped, mask= mask)
return result
def select_roi(self, order: int):
'''
This function allows the manual segmentation of the ROI.
It calls another function (selection) and return the coordinates of the ROI.
Finally, it shows the result images in the main UI.