-
Notifications
You must be signed in to change notification settings - Fork 1
/
gui.py
1770 lines (1456 loc) · 60.5 KB
/
gui.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
"""
Project Needle
Auburn University
Senior Design | Fall 2019
Team Members:
Andrea Walker, Rich Surgenor, Jackson Solley, Jacob Hagewood,
Justin Sutherland, Laura Grace Ayers.
"""
# GUI for Project Needle, mainly allowing the user to view ideal points for needle insertion to veins.
from PyQt5.QtCore import Qt, QObject, QCoreApplication, QSize, QThread, QFile, QTextStream, QPoint, pyqtSignal, \
QTimer, QEventLoop
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QPixmap, QPainter, QImage, QColor, QKeySequence, QSurfaceFormat, QOpenGLVertexArrayObject
import numpy
import cv2
import sys
import api
import time
import os
import forwarding_server
from common import log_image
from traceback import print_tb
import platform
from OpenGL import GL
#from OpenGL.raw.GL.APPLE.vertex_array_object import *
from OpenGL import GLU
from math import pow, sqrt, asin, pi
import common
from objloader import OBJ
if not platform.uname()[0] == 'Windows':
USING_PI = os.uname()[4][:3] == 'arm'
else:
USING_PI = False
###############
# Non-Settings:
AUTOMATIC = 0
SEMIAUTOMATIC = 1
MANUAL = 2
###############
# Settings
DEFAULT_MODE = AUTOMATIC
BORDER_SIZE = 10
HALF_BORDER_SIZE = BORDER_SIZE/2
FPS = 5
GFX_ON_START = True
GFX_AUTO_ROTATE = True
STILL_IMAGE_CAPTURE = 0 # broken, don't use.
"""
To see how much clipping when CLIP_RAILS_THROUGH_NUMPY see prostick_lib.py
Allows cropping what the selection algo sees without cropping the actual picture.
disadvantage: isn't done before preprocessing..
"""
if USING_PI:
from pivideostream import PiVideoStream
LOGGING = 1
DARK_THEME = 1
SAVE_RAWIMG = 1 # Save image after capture
GANTRY_ON = 1 # Control Gantry on/off for normal/mock modes
MOCK_MODE_IMAGE_PROCESSING = 0 # Fake image processing but still run everything else
MOCK_MODE_GANTRY = 0 # Fake Gantry connection but still run everything else
CAMERA_RESOLUTION_WIDTH = 1920
CAMERA_RESOLUTION_HEIGHT = 1080
CROPPING_ENABLED = 1
CROPPED_RESOLUTION_WIDTH = 1080
CROPPED_RESOLUTION_HEIGHT = 1080
GUI_IMAGE_SIZE_WIDTH = 540 # 640
GUI_IMAGE_SIZE_HEIGHT = 540 # 368
CLIP_RAILS_THROUGH_NUMPY = False
else:
DARK_THEME = 0
SAVE_RAWIMG = 0
LOGGING = 0
GANTRY_ON = 1
MOCK_MODE_IMAGE_PROCESSING = 0
MOCK_MODE_GANTRY = 1
CAMERA_RESOLUTION_WIDTH = 1280
CAMERA_RESOLUTION_HEIGHT = 720
CROPPING_ENABLED = 0
CROPPED_RESOLUTION_WIDTH = 1000
CROPPED_RESOLUTION_HEIGHT = 720
GUI_IMAGE_SIZE_WIDTH = 640
GUI_IMAGE_SIZE_HEIGHT = 360
CLIP_RAILS_THROUGH_NUMPY = False
def set_forwarding_settings():
global CAMERA_RESOLUTION_WIDTH,CAMERA_RESOLUTION_HEIGHT, \
GUI_IMAGE_SIZE_WIDTH,GUI_IMAGE_SIZE_HEIGHT,CROPPING_ENABLED, \
CROPPED_RESOLUTION_WIDTH,CROPPED_RESOLUTION_HEIGHT,SCALE_FACTOR, \
LOGGING, SAVE_RAWIMG, GANTRY_ON, MOCK_MODE_GANTRY, MOCK_MODE_IMAGE_PROCESSING, \
CLIP_RAILS_THROUGH_NUMPY
LOGGING = 1
GANTRY_ON = 1
MOCK_MODE_IMAGE_PROCESSING = 0
MOCK_MODE_GANTRY = 0
SAVE_RAWIMG = 1
"""
Note that on a full size 3280x2464 img that the gantry rails are approx:
min_x = min_x + 760
max_x = max_x - 1020
So approx crop would be: 1500x2464
"""
CAMERA_RESOLUTION_WIDTH = 1000 #3280#
CAMERA_RESOLUTION_HEIGHT = 1000 #2464#
#GUI_IMAGE_SIZE_WIDTH = CAMERA_RESOLUTION_WIDTH/4
#GUI_IMAGE_SIZE_HEIGHT = CAMERA_RESOLUTION_HEIGHT/4
# one problem with cropping height is we only want to crop the max y
# TODO: make cropping with y only for max_y (so bottom isnt cropped)
CROPPING_ENABLED = 0
CROPPED_RESOLUTION_WIDTH = 840 #1500
CROPPED_RESOLUTION_HEIGHT = 1000 # clip height because uneven distribution of light
if not CROPPING_ENABLED:
factor = 2
GUI_IMAGE_SIZE_WIDTH = CAMERA_RESOLUTION_WIDTH / factor
GUI_IMAGE_SIZE_HEIGHT = CAMERA_RESOLUTION_HEIGHT / factor
else:
factor = 2
GUI_IMAGE_SIZE_WIDTH = CROPPED_RESOLUTION_WIDTH / factor
GUI_IMAGE_SIZE_HEIGHT = CROPPED_RESOLUTION_HEIGHT / factor
CLIP_RAILS_THROUGH_NUMPY = True
FAKE_INPUT_IMG = 1
if FAKE_INPUT_IMG:
FAKE_INPUT_IMG_NAME = "./last_tests/male 23 cau.jpg"
CAMERA_RESOLUTION_WIDTH = 1000#3280
CAMERA_RESOLUTION_HEIGHT = 1000#2464
GUI_IMAGE_SIZE_WIDTH = 500 #550 # 640
GUI_IMAGE_SIZE_HEIGHT = 500 # 368
CROPPING_ENABLED = 0
CROPPED_RESOLUTION_WIDTH = 2200
CROPPED_RESOLUTION_HEIGHT = 2464
CLIP_RAILS_THROUGH_NUMPY=True
def ui_main(fwd=False):
"""
Initialize main UI
:return: None
"""
global FORWARDING
FORWARDING = fwd
if fwd:
set_forwarding_settings()
app = QApplication(sys.argv)
if DARK_THEME:
file = QFile("./assets/dark.qss")
file.open(QFile.ReadOnly | QFile.Text)
stream = QTextStream(file)
app.setStyleSheet(stream.readAll())
ui = MainWindow()
sys.exit(app.exec_())
def _createCntrBtn(*args):
l = QHBoxLayout()
for arg in args:
l.setSpacing(30)
l.setAlignment(arg, Qt.AlignCenter)
#l.addStretch()
l.addWidget(arg)
#l.addStretch()
return l
def get_effective_image_height():
if CROPPING_ENABLED:
return CROPPED_RESOLUTION_HEIGHT
else:
return CAMERA_RESOLUTION_HEIGHT
def get_effective_image_width():
if CROPPING_ENABLED:
return CROPPED_RESOLUTION_WIDTH
else:
return CAMERA_RESOLUTION_WIDTH
def get_processor():
if MOCK_MODE_IMAGE_PROCESSING:
return api.ProcessorMock()
else:
if CROPPING_ENABLED:
return api.Processor(CROPPED_RESOLUTION_WIDTH, CROPPED_RESOLUTION_HEIGHT, clip_rails_numpy=CLIP_RAILS_THROUGH_NUMPY)
else:
return api.Processor(CAMERA_RESOLUTION_WIDTH, CAMERA_RESOLUTION_HEIGHT, clip_rails_numpy=CLIP_RAILS_THROUGH_NUMPY)
def get_controller():
if MOCK_MODE_GANTRY:
return api.GantryControllerMock()
else:
return api.GantryController()
class FakeCamera:
def __init__(self):
self.rawframe = cv2.imread(FAKE_INPUT_IMG_NAME, 1)
# self.rawframe = cv2.resize(self.rawframe, dsize=(GUI_IMAGE_SIZE_WIDTH, GUI_IMAGE_SIZE_HEIGHT), interpolation=cv2.INTER_CUBIC)
# cv2.imwrite('testproc.jpg', self.rawframe)
self.opened = False
#self.rawframe = cv2.cvtColor(self.rawframe, cv2.COLOR_RGB2BGR)
def get_frame(self):
return self.rawframe
def start(self):
self.opened = True
def stop(self):
pass
class Camera:
def __init__(self, camera_num):
self.cap = None
self.camera_num = camera_num
self.opened = False
def start(self):
self.cap = cv2.VideoCapture(self.camera_num)
self.set_resolution(CAMERA_RESOLUTION_WIDTH, CAMERA_RESOLUTION_HEIGHT)
self.opened = True
def is_open(self):
return self.opened
def set_brightness(self, value):
pass
def set_resolution(self, width, height):
self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
def get_frame(self, rbg2rgb=False):
ret, frame = self.cap.read()
if rbg2rgb:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
return frame
def stop(self):
self.cap.release()
def __str__(self):
return 'OpenCV Camera {}'.format(self.camera_num)
class StatusThread(QThread):
"""
Thread maintaining status assets, because if main thread is halted qt will be nonoperational.
"""
def __init__(self, parent, gantry_status, processing_status):
super().__init__()
self.parent = parent
self.gantry_status = gantry_status
self.processing_status = processing_status
if GANTRY_ON:
self.gc = api.GantryController(MOCK_MODE_GANTRY)
self.gc.start()
self.msleep(100)
self.last_msg = ""
self.obj_rotation_thread = None
#self.gc.send_msg(api.REQ_ECHO_MSG, "Connected to Arduino!")
def run(self):
while True:
if self.gc:
self.gantry_status.showMessage("Gantry: " + self.gc.msg)
if GFX_AUTO_ROTATE:
if self.parent.finished_init and self.last_msg != self.gc.msg:
if not self.obj_rotation_thread:
self.obj_rotation_thread = ObjectRotationThread(self.parent, self.parent.gfx_widget)
# self.obj_rotation_thread.th
self.obj_rotation_thread.start()
self.parent.obj_rotation_thread = self.obj_rotation_thread
while not self.obj_rotation_thread.obj_rotater:
pass
#print('CURRENT THREAD 1: ' + self.currentThread().objectName())
self.obj_rotation_thread.obj_rotater.msg_changed.emit()
self.last_msg = self.gc.msg
self.msleep(100)
class PreviewThread(QThread):
"""
Thread for the input image.
"""
def __init__(self, camera, video_frame):
super().__init__()
self.camera = camera
self.video_frame = video_frame
self.rawframe = None
self.inputbox = video_frame
def next_frame_slot(self):
self.rawframe = self.camera.get_frame()
# Sometimes the first few frame are null, so we will ignore them.
if self.rawframe is None:
return
if CROPPING_ENABLED:
self.rawframe = common.cropND(self.rawframe, (CROPPED_RESOLUTION_HEIGHT, CROPPED_RESOLUTION_WIDTH))
#savemat('data.mat', {'frame': frame, 'framee': framee})
#img = cv2.resize(self.rawframe, (GUI_IMAGE_SIZE_WIDTH, GUI_IMAGE_SIZE_HEIGHT))
rawframe_conv = cv2.cvtColor(self.rawframe, cv2.COLOR_BGR2RGB)
img = QImage(numpy.asarray(rawframe_conv, order='C'), rawframe_conv.shape[1], rawframe_conv.shape[0], QImage.Format_RGB888)
pix = QPixmap.fromImage(img)
pix = pix.scaled(GUI_IMAGE_SIZE_WIDTH,GUI_IMAGE_SIZE_HEIGHT, Qt.IgnoreAspectRatio)
#self.video_frame.setPixmap(pix)
self.video_frame.img = pix
self.video_frame.start()
self.video_frame.update() # rather than repaint bc flicker
def run(self):
while True:
self.next_frame_slot()
time_slept = time_slept = int((float(1)/FPS) * 1000)
self.msleep(time_slept) # TODO: make this settable
qApp.processEvents()
class QImageBox(QGroupBox):
def __init__(self, text):
super(QGroupBox, self).__init__(text)
#self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
class QProcessedImageGroupBox(QGroupBox):
def __init__(self, parent, text, img):
super(QGroupBox, self).__init__(text)
self.parent = parent
self._layout = QVBoxLayout()
self._layout.setSpacing(0)
self._layout.setSizeConstraint(QLayout.SetMinimumSize)
self.split_holder = QWidget()
self.split_layout = QHBoxLayout()
self.split_layout.setSpacing(0)
self.coord_holder = QWidget()
#self.coord_holder.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
self.coord_layout = QVBoxLayout()
self.coord_layout.setSpacing(0)
self.coord_holder.setLayout(self.coord_layout)
self.settings_holder = QWidget()
self.settings_layout = QVBoxLayout()
self.settings_layout.setSpacing(0)
self.settings_holder.setLayout(self.settings_layout)
self.setLayout(self._layout)
self.img = img
self.image_label = QImageLabel("", img)
self.display_coords = QLabel("Coordinates(pixels): ")
self.display_injection_site_label = QLabel("Injection Site(mm): \nInjection Site(steps): ")
self.display_coords.setStyleSheet("color: red");
self.display_injection_site_label.setStyleSheet("color: red");
#self.coord_layout.addWidget(self.image_label)
self._layout.addWidget(self.image_label)
self.coord_layout.addWidget(self.display_coords)
self.coord_layout.addWidget(self.display_injection_site_label)
self.points = None
self.chosen = None
self.use_masked_image = QCheckBox("Use Masked Image")
self.use_masked_image.setChecked(True)
self.use_masked_image.clicked.connect(self.change_use_masked_img)
self.settings_layout.addWidget(self.use_masked_image)
#self.settings_layout.setAlignment(Qt.AlignTop)
self.split_layout.addWidget(self.coord_holder)
self.split_layout.addWidget(self.settings_holder)
self.split_holder.setLayout(self.split_layout)
self._layout.setSizeConstraint(QLayout.SetFixedSize)
self._layout.addWidget(self.split_holder)
# Configure mouse press on processed image widget
self.image_label.mousePressEvent = self.get_pos
#self.image_label.connect(self, pyqtSignal("clicked()"), self.getPos)
#self.coord_holder.sizeHint = lambda: QSize(50, 50)
self.coord_holder.setFixedHeight(70)
self.coord_holder.setFixedWidth(360)
self.settings_holder.setFixedHeight(64)
def get_layout(self):
return self._layout
def update_image(self, img):
self.image_label.img = img
def reset(self):
self.image_label.set_status(False)
self.image_label.img = None
def get_pos(self, event):
if not self.image_label.img:
print('User tried to click point before any existed.')
return
selected_x = event.pos().x() - HALF_BORDER_SIZE - 5
selected_y = event.pos().y() - HALF_BORDER_SIZE - 5
mode = self.parent.get_active_mode()
if mode == MANUAL:
# because the top-left corner of the blue reticle is where it actually starts painting,
# and we want our point that will be converted to mm to be as accurate as possible..
actual_selected_x = selected_x + 5
actual_selected_y = selected_y + 5
# now we scale points up instead... :) at a loss of accuracy :(
factor_x = float(CAMERA_RESOLUTION_WIDTH) / GUI_IMAGE_SIZE_WIDTH
factor_y = float(CAMERA_RESOLUTION_HEIGHT) / GUI_IMAGE_SIZE_HEIGHT
scaled_x = int(round(factor_x * actual_selected_x))
scaled_y = int(round(factor_y * actual_selected_y))
self.points = [(int(selected_x), int(selected_y))]
self.parent.processor.centers = [(scaled_x, scaled_y)]
chosen = 0 # only one point...
self.chosen = 0
if self.use_masked_image.isChecked():
self.parent.draw_processed_img_with_pts(self.parent.masked_img, self.points, chosen)
else:
self.parent.draw_processed_img_with_pts(self.parent.last_rawimg, self.points, chosen)
self.image_label.repaint()
self.parent.display_coordinates(self.parent.output_box.points[chosen][0]*float((CAMERA_RESOLUTION_WIDTH/GUI_IMAGE_SIZE_WIDTH)),
self.parent.output_box.points[chosen][1]*float((CAMERA_RESOLUTION_HEIGHT/GUI_IMAGE_SIZE_HEIGHT)))
self.parent.process_point(index=chosen)
else:
best_x = 10000
best_y = 10000
chosen = -1
# check closest point
for i in range(0, len(self.points)):
point = self.points[i]
x,y = point
diff_x = abs(selected_x - x)
diff_y = abs(selected_y - y)
diff_sum = diff_x + diff_y
if diff_sum < best_x+best_y:
best_x = diff_x
best_y = diff_y
#print("diff_x: " + str(selected_x - x) + " diff_y: " + str(selected_y - y))
chosen = i
self.chosen = i
#print("best_x: " + str(best_x) + " best_y: " + str(best_y))
self.parent.draw_processed_img_with_pts(self.image_label.img, self.points, chosen)
self.parent.display_coordinates(self.parent.output_box.points[chosen][0]*float((CAMERA_RESOLUTION_WIDTH/GUI_IMAGE_SIZE_WIDTH)),
self.parent.output_box.points[chosen][1]*float((CAMERA_RESOLUTION_HEIGHT/GUI_IMAGE_SIZE_HEIGHT)))
self.parent.process_point(index=chosen)
def change_use_masked_img(self):
if not self.parent.last_rawimg:
QMessageBox.information(None, 'Not available', 'Capture an image first.', QMessageBox.Ok)
self.use_masked_image.setChecked(True)
return
mode = self.parent.get_active_mode()
if mode == MANUAL and not self.points:
if self.use_masked_image.isChecked():
self.parent.draw_output_img(self.parent.masked_img)
else:
self.parent.draw_output_img(self.parent.last_rawimg)
else:
if self.use_masked_image.isChecked():
self.parent.draw_processed_img_with_pts(self.parent.masked_img, self.points, self.chosen)
else:
self.parent.draw_processed_img_with_pts(self.parent.last_rawimg, self.points, self.chosen)
class QImageLabel(QLabel):
def __init__(self, _, img):
super(QLabel, self).__init__(_)
self.setFrameShape(QFrame.Panel)
self.setFrameShadow(QFrame.Raised)
self.setLineWidth(3)
self.setMidLineWidth(3)
self.img = img
self.setSizePolicy(QSizePolicy.Fixed,QSizePolicy.Fixed)
self.done = False
def set_status(self, status):
self.done = status
self.repaint()
def paintEvent(self, e):
QLabel.paintEvent(self, e)
p = QPainter(self)
if self.done:
p.drawPixmap(QPoint(HALF_BORDER_SIZE, HALF_BORDER_SIZE), self.img)
def sizeHint(self):
return QSize(GUI_IMAGE_SIZE_WIDTH + BORDER_SIZE, GUI_IMAGE_SIZE_HEIGHT + BORDER_SIZE)
class QInputBox(QLabel):
def __init__(self, _, img):
super(QLabel, self).__init__(_)
self.setFrameShape(QFrame.Panel)
self.setFrameShadow(QFrame.Raised)
self.setLineWidth(3)
self.setMidLineWidth(3)
self.img = img
self.setSizePolicy(QSizePolicy.Fixed,QSizePolicy.Fixed)
self.started = False
def set_status(self, status):
pass
def paintEvent(self, e):
QLabel.paintEvent(self, e)
p = QPainter(self)
if self.started:
p.drawPixmap(QPoint(HALF_BORDER_SIZE, HALF_BORDER_SIZE), self.img)
def start(self):
self.started = True
def sizeHint(self):
return QSize(GUI_IMAGE_SIZE_WIDTH + BORDER_SIZE, GUI_IMAGE_SIZE_HEIGHT + BORDER_SIZE)
class QModeMenuWidget(QWidget):
def __init__(self, parent):
super(QWidget, self).__init__()
self.titles = ["Automatic Mode", "Semiautomatic Mode", "Manual Mode"]
self.checkboxes = []
self.checkboxes_layout = QHBoxLayout()
self.group = QButtonGroup()
self.parent = parent
self.current = 0
for i in range(0, len(self.titles)):
title = self.titles[i]
checkbox = QCheckBox(title)
checkbox.setCheckState(Qt.Unchecked)
self.checkboxes.append(checkbox)
self.group.addButton(checkbox, i)
self.checkboxes_layout.addWidget(self.checkboxes[i])
self.checkboxes[DEFAULT_MODE].setCheckState(Qt.Checked)
self.group.buttonClicked.connect(self.mode_change_event)
self.checkboxes_layout.setAlignment(Qt.AlignLeft)
self.checkboxes_layout.setSpacing(30)
self.setLayout(self.checkboxes_layout)
def mode_change_event(self, button):
self.parent.gfx_widget.window.gfx_widget.pic_enabled = False
self.parent.output_box.reset()
self.parent.gantry_status.showMessage("Gantry: ")
self.parent.processing_status.showMessage("Processing: ")
pass
class MainWindow(QMainWindow):
"""
Main window for application.
"""
def __init__(self):
super(QMainWindow, self).__init__()
#self.resize(1200, 800)
self.camera = None
if FAKE_INPUT_IMG:
self.camera = FakeCamera()
else:
if USING_PI:
self.camera = PiVideoStream(resolution=(CAMERA_RESOLUTION_WIDTH, CAMERA_RESOLUTION_HEIGHT))
else:
if FORWARDING:
self.camera = forwarding_server.ForwardingCamera()
else:
self.camera = Camera(0)
self.camera.start()
self.processor = get_processor()
self.wid = QWidget(self)
self.setCentralWidget(self.wid)
self.setWindowTitle('Project Needle')
self._layout = QBoxLayout(QBoxLayout.TopToBottom, self.wid)
self._layout.setSpacing(0)
self.wid.setLayout(self._layout)
self.gantry_status = QStatusBar()
self._layout.addWidget(self.gantry_status)
self.processing_status = QStatusBar()
self._layout.addWidget(self.processing_status)
self.checkbox_widget = QModeMenuWidget(self)
self._layout.addWidget(self.checkbox_widget)
#self._layout.addWidget(self.centralWidget)
self.pic_widget = QImageBox("Image View")
self.pics_hbox = QHBoxLayout(self.pic_widget)
self.pics_hbox.setAlignment(Qt.AlignHCenter)
self.pics_hbox.setSpacing(10)
self.pic_widget.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
self.video_frame = QInputBox("", None)
self.input_box = QGroupBox("Input Image") #QImageGroupBox("Input Image", self.video_frame)
self.gfx_cb_autorotate = QLabel("")#QCheckBox("GFX Auto-Rotate")
#self.gfx_cb_autorotate.setChecked(GFX_AUTO_ROTATE)
#self.gfx_cb_autorotate.clicked.connect(self.gfx_cb_autorotate_event)
input_box_layout = QVBoxLayout()
self.input_box.setLayout(input_box_layout)
input_box_layout.addWidget(self.video_frame)
input_box_layout.addWidget(self.gfx_cb_autorotate)
self.pics_hbox.addWidget(self.input_box) #(self.lb)
self.feed = PreviewThread(self.camera, self.video_frame)
self.feed.start()
self.finished_init = False
# Init thread that manages Gantry...
self.status_thread = StatusThread(self, self.gantry_status, self.processing_status)
self.status_thread.setObjectName("Status Thread")
self.status_thread.start()
self.gc = self.status_thread.gc
self.output_box = QProcessedImageGroupBox(self, "Processed Image", None)
self.pics_hbox.addWidget(self.output_box)
self._layout.addWidget(self.pic_widget)
# buttons
btn_process_img = QPushButton("Capture Image")
btn_process_img.clicked.connect(self.process_image_event)
btn_gantry_start = QPushButton("Start Gantry")
btn_gantry_start.clicked.connect(self.gantry_start_event)
btn_reset = QPushButton("Reset")
btn_reset.clicked.connect(self.reset_event)
btn_calibrate = QPushButton("Calibrate")
btn_calibrate.clicked.connect(self.calibrate_event)
btn_close = QPushButton("Close")
btn_close.clicked.connect(self.close_event)
btn_settings = QPushButton("Settings")
btn_settings.clicked.connect(self.settings_event)
#btn_debug_cmds = QPushButton("Debug Cmds")
#btn_debug_cmds.clicked.connect(self.debug_cmds_event)
gfx_view = QPushButton("GFX View")
gfx_view.clicked.connect(self.gfx_view_event)
self.btn_widget = QWidget()
btn_panel = _createCntrBtn(gfx_view, btn_settings, btn_reset, btn_calibrate, btn_close)
self.btn_widget.setLayout(btn_panel)
self._layout.addWidget(self.btn_widget)
self.btn_widget2 = QWidget()
btn_panel2 = _createCntrBtn(btn_process_img, btn_gantry_start)
self.btn_widget2.setLayout(btn_panel2)
self._layout.addWidget(self.btn_widget2)
self.setAttribute(Qt.WA_DeleteOnClose, True)
self.last_rawimg = None
self.masked_img = None
self.move(self.window().x()+450, self.window().y()+20)
# Init graphics
if GFX_ON_START:
self.start_gfx_widget()
else:
self.gfx_widget = None
#self.status_thread.moveToThread(self.obj_rotation_thread.thread())
#self.obj_rotation_thread.moveToThread(self.status_thread.thread())
self.finished_init = True
QApplication.processEvents()
self.show()
QApplication.processEvents()
def start_gfx_widget(self):
self.gfx_widget = GraphicsWidget(self)
self.gfx_widget.setObjectName("Graphics Thread")
#self.gfx_widget.start()
self.gc.gfx_widget = self.gfx_widget
def gfx_cb_autorotate_event(self):
pass
def get_active_mode(self):
return self.checkbox_widget.group.checkedId() # will correspond to modes
def display_coordinates(self, x, y):
self.output_box.display_coords.setText("Coordinates(pixels): x: " + str(x) + " y: " + str(y))
self.output_box.display_coords.repaint()
def display_injection_site(self, x, y, x_steps, y_steps):
self.output_box.display_injection_site_label.setText("Injection Site(mm): x: {0:.2f} away. y: {1:.2f} down.".format(x, y) \
+ "\nInjection Site(steps): x: " + str(x_steps) + " away. y: " + str(y_steps) + " down.")
self.output_box.display_injection_site_label.repaint()
def clear_coordinates(self):
self.output_box.display_coords.setText("Coordinates(pixels): ")
self.output_box.display_coords.repaint()
def clear_injection_site(self):
self.output_box.display_injection_site_label.setText("Injection Site(mm): \nInjection Site(steps): ")
self.output_box.display_injection_site_label.repaint()
#class ProcessingThread(QThread): TODO: do we need this?
def draw_output_img(self, img):
result = QPixmap(img.width(), img.height())
painter = QPainter(result)
# Paint final images on result
painter.drawPixmap(0, 0, img)
painter.end()
self.output_box.update_image(result)
self.output_box.image_label.set_status(True)
def draw_processed_img_with_pts(self, processed_img_scaled, scaled_points, chosen):
"""
:param processed_img_scaled: scaled version of image
:param scaled_points: scaled points
:param chosen: index of point chosen from list of scaled_points
:return: currently None
"""
# Create Overlay Img with Transparency
overlay_img = QPixmap("assets/transp_bluedot.png") # transparent_reticle.png")
overlay_alpha = QPixmap(overlay_img.size())
overlay_alpha.fill(Qt.transparent) # force alpha channel
# Paint overlay_img onto overlay_alpha
overlay_alpha_cpy = overlay_alpha.copy()
painter = QPainter(overlay_alpha)
painter.drawPixmap(0, 0, overlay_img)
painter.end()
painter = QPainter(overlay_alpha_cpy)
mask = overlay_img.createMaskFromColor(Qt.transparent, Qt.MaskInColor)
painter.setPen(QColor(0, 255, 0))
painter.drawPixmap(overlay_alpha.rect(), mask, mask.rect())
painter.end()
# processed_img = QPixmap("image3_results_n1.jpg")
overlay_scaled = overlay_alpha.scaled(10, 10, Qt.KeepAspectRatio)
overlay_scaled_green = overlay_alpha_cpy.scaled(10, 10, Qt.KeepAspectRatio)
result = QPixmap(processed_img_scaled.width(), processed_img_scaled.height())
result.fill(Qt.transparent) # force alpha channel
painter = QPainter(result)
# Paint final images on result
painter.drawPixmap(0, 0, processed_img_scaled)
for i in range(0, len(scaled_points)):
point = scaled_points[i]
if i == chosen:
#x += 31
#y += 35
painter.drawPixmap(point[0], point[1], overlay_scaled_green)
else:
painter.drawPixmap(point[0], point[1], overlay_scaled)
painter.end()
self.output_box.points = scaled_points
self.output_box.update_image(result)
self.output_box.image_label.set_status(True)
def process_point(self, **kwargs):
success = 0
try:
if 'index' in kwargs:
injection_site_in_mm = self.processor.get_injection_site_relative_to_point(index=kwargs['index'])
else:
injection_site_in_mm = self.processor.get_injection_site_relative_to_point()
success = 1
except IndexError as e:
# This occurs sometimes.. usually during slice_grid from spookylib...
print("{} : {}".format(type(e), e))
print_tb(e.__traceback__)
QMessageBox.information(None, 'Error 1', 'Getting injection site in mm failed.', QMessageBox.Ok)
if LOGGING and 'index' not in kwargs: # only log if in automatic mode...
log_image(self.processor.img_in, "error_1_num")
except Exception as e:
print("=====Unknown Error getting injection site...=====")
print("{} : {}".format(type(e), e))
print_tb(e.__traceback__)
if LOGGING and 'index' not in kwargs:
log_image(self.processor.img_in, "error_site_unk_num")
if success:
print("Coordinate in mm: x: {} y: {}".format(injection_site_in_mm[0], injection_site_in_mm[1]))
self.gc.coordinate = self.processor.get_injection_site_in_steps_relative_to_point(injection_site_in_mm)
# send coordinate
self.gc.send_coordinate(self.gc.coordinate[0], self.gc.coordinate[1])
self.display_injection_site(injection_site_in_mm[0], injection_site_in_mm[1], self.gc.coordinate[0],
self.gc.coordinate[1])
QCoreApplication.processEvents()
"""
Events
"""
def process_image_event(self):
"""
Receive processed image and use the received points to display a final image.
:return: None
"""
#TODO: redo this whole function
print("Processing...")
# clear old
self.clear_coordinates()
self.clear_injection_site()
self.output_box.points = None
self.output_box.chosen = None
self.processor.centers = None
self.processor.selection = None
self.output_box.use_masked_image.setChecked(True)
if STILL_IMAGE_CAPTURE: # should only be on if picamera
raw = self.camera.capture_still_image()
else:
raw = self.feed.rawframe
try:
if not raw:
QMessageBox.information(None, 'No input image', 'Woops! No input image to process.', QMessageBox.Ok)
return
except:
#numpy is stupid so it tries to throw an exception here if the image exists.
pass
# curious enough cvting to correct colors seems to throw off pts
#if not USING_PI and not FORWARDING:
#if isinstance(self.camera, FakeCamera) or isinstance(self.camera, Camera):
raw = cv2.cvtColor(raw, cv2.COLOR_BGR2RGB)
#if SAVE_RAWIMG:
cv2.imwrite('gui-rawimg.jpg', raw)
height, width, channels = raw.shape
bytes_per_line = width * 3
q_img = QImage(raw.copy().data, width, height, bytes_per_line, QImage.Format_RGB888)
processed_img = QPixmap.fromImage(q_img)
processed_img_scaled = processed_img.scaled(GUI_IMAGE_SIZE_WIDTH, GUI_IMAGE_SIZE_HEIGHT, Qt.IgnoreAspectRatio)
self.last_rawimg = processed_img_scaled
self.draw_output_img(processed_img_scaled)
QCoreApplication.processEvents()
self.processing_status.showMessage("Processing: Applying thresholding...")
#grayimg = cv2.imread("justin_python/justin4.jpg", 0)
grayimg = cv2.cvtColor(raw, cv2.COLOR_RGB2GRAY) # TODO: may need to be different per camera
clahe_img = self.processor.apply_clahe(grayimg)
self.gfx_widget.window.gfx_widget.change_image(clahe_img)
self.gfx_widget.window.gfx_widget.pic_enabled = True
self.gfx_widget.window.gfx_widget.update()
# we gray now...
height, width = clahe_img.shape
bytes_per_line = width
q_img = QImage(clahe_img.copy().data, width, height, bytes_per_line, QImage.Format_Grayscale8)
processed_img = QPixmap.fromImage(q_img)
processed_img_scaled = processed_img.scaled(GUI_IMAGE_SIZE_WIDTH, GUI_IMAGE_SIZE_HEIGHT, Qt.IgnoreAspectRatio)
#scaled_points = [(x / SCALE_FACTOR, y / SCALE_FACTOR) for x, y in points]
self.draw_output_img(processed_img_scaled)
self.output_box.repaint()
QCoreApplication.processEvents()
self.processing_status.showMessage("Processing: Applying mask...")
QThread.msleep(1000)
thresholding_img = self.processor.apply_thresholding(clahe_img)
height, width = thresholding_img.shape
bytes_per_line = width
q_img = QImage(thresholding_img.copy().data, width, height, bytes_per_line, QImage.Format_Grayscale8)
processed_img = QPixmap.fromImage(q_img)
processed_img_scaled = processed_img.scaled(GUI_IMAGE_SIZE_WIDTH, GUI_IMAGE_SIZE_HEIGHT, Qt.IgnoreAspectRatio)
self.masked_img = processed_img_scaled.copy()
self.draw_output_img(processed_img_scaled)
if self.get_active_mode() == MANUAL:
self.processing_status.showMessage("Processing: Mask complete! You can now manually select a point...")
return
self.processing_status.showMessage("Processing: Calculating optimal points...")
QCoreApplication.processEvents()
#QThread.msleep(1000)
try:
centers = self.processor.get_optimum_points(thresholding_img)
except Exception as e:
self.processing_status.showMessage("Processing: Not enough centers found...")
print("=====Unknown Error getting centers..=====")
print("{} : {}".format(type(e), e))
print_tb(e.__traceback__)
if LOGGING:
log_image(self.processor.img_in, "error_3_centers_num")
return # we failed...
#numpy.savetxt('test2.txt', centers, fmt='%d')
points = numpy.copy(centers)
scalex = float(get_effective_image_width()) / GUI_IMAGE_SIZE_WIDTH
scaley = float(get_effective_image_height()) / GUI_IMAGE_SIZE_HEIGHT
#scalex = int(scalex)
#scaley = int(scaley)
for point in points:
point[0] = round(point[0] / scalex)
point[1] = round(point[1] / scaley)
point[0] = point[0] + HALF_BORDER_SIZE - 5
point[1] = point[1] + HALF_BORDER_SIZE - 5
self.output_box.points = points
self.draw_processed_img_with_pts(processed_img_scaled, points, -1)
if self.get_active_mode() == AUTOMATIC:
self.processing_status.showMessage("Processing: Searching for final selection...")
QCoreApplication.processEvents()
#QThread.msleep(2000)
final_selection = self.processor.get_final_selection(numpy.shape(raw), centers)
if final_selection:
self.display_coordinates(self.output_box.points[final_selection][0],self.output_box.points[final_selection][1]) # TODO what if no coordinate...
self.output_box.chosen = final_selection
self.draw_processed_img_with_pts(processed_img_scaled, points, final_selection)
self.processing_status.showMessage("Processing: Final selection complete...")
self.process_point()
else:
self.processing_status.showMessage("Processing: Final selection failed, but select a point!...")
QMessageBox.information(None, 'Error 2', 'No final selection was returned.', QMessageBox.Ok)
if LOGGING:
log_image(self.processor.img_in, "error_2_num")
else:
self.processing_status.showMessage("Processing: Optimal points found!")
def gantry_start_event(self):
self.gantry_status.showMessage("Starting Gantry...")
self.gc.send_msg(api.REQ_GO_TO_WORK)
def reset_event(self):
self.gc.send_msg(api.REQ_RESET)
self.status_thread.gc.stop()
del self.status_thread.gc
self.status_thread.gc = None
time.sleep(1) # not okay probably
self.status_thread.gc = api.GantryController(MOCK_MODE_GANTRY)
self.status_thread.setObjectName("Gantry Controller")
self.status_thread.gc.start()
#self.output_box.image_label.set_status(False)
# TODO: actually make this reset the entire state of the GUI
def calibrate_event(self):
QMessageBox.information(None, 'Calibration', 'pretty sure this is a meme now.', QMessageBox.Ok)
# TODO: deem if this is a necessary functionality or if we will keep it in arduino code
def close_event(self):
qApp.exit()
def settings_event(self):
pass
def debug_cmds_event(self):
for i in range(0, 8000):
self.gfx_widget.move_needle(2, 0)
pass
def gfx_view_event(self):
if self.gfx_widget:
if self.gfx_widget.window.isHidden():
self.gfx_widget.window.show()
else:
self.gfx_widget.window.hide()
else: