-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustom_widgets.py
1361 lines (1019 loc) · 50.8 KB
/
custom_widgets.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
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 7 12:01:56 2023
@author: Rakhul Raj
"""
import sys
import os
import re
from multiprocessing import Pool
from threading import Thread
from functools import partial
from pathlib import Path
from typing import TYPE_CHECKING, Union
from typing import TypeVar, Tuple, Any, List
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import cv2
from PyQt5.QtGui import QMouseEvent, QPainter, QPen
from PyQt5.QtWidgets import (QMainWindow,
QApplication,
QMessageBox,
QFileDialog,
QLabel,
QShortcut,
QSizePolicy,
QWidget,
QPushButton,
QDialog
)
from PyQt5 import uic
from PyQt5.QtCore import QSize, QPoint, Qt, QUrl
from PyQt5.QtGui import QImage, QPixmap, QKeySequence, QDesktopServices
# iconSize = QSize(3000,3000)
# from werkzeug.serving import make_server
from mymodule.utils import decorate_all_methods
from mymodule.exceptions import exception_handler
import icons
import processing as ps
from api import MyFlaskApp
import imageviewer
# if TYPE_CHECKING:
from multiprocessing.pool import Pool as MPPool
if sys.version_info >= (3, 9):
# Define custom types
GrayImage = TypeVar('GrayImage', bound= np.ndarray[Tuple[Any, Any], np.uint8])
BGRImage = TypeVar('BGRImage', bound= np.ndarray[Tuple[Any, Any, 3], np.uint8])
Image = TypeVar('Image', bound= np.ndarray[Tuple[Any, Any, 0|3], np.uint8])
Contour = TypeVar('Contour', bound= np.ndarray[Tuple[Any, 1, 2], np.uint8])
# end
else:
# Define custom types
GrayImage = TypeVar('GrayImage', bound= np.ndarray)
BGRImage = TypeVar('BGRImage', bound= np.ndarray)
Image = TypeVar('Image', bound= np.ndarray)
Contour = TypeVar('Contour', bound= np.ndarray)
if getattr(sys, 'frozen', False):
# If the application is run as a bundle, the PyInstaller bootloader
# extends the sys module by a flag frozen=True and sets the app
# path into variable _MEIPASS'.
application_path = Path(sys._MEIPASS)
else:
application_path = Path(os.path.dirname(os.path.abspath(__file__)))
class PoolManager:
def __init__(self, num_workers):
self.num_workers = num_workers
self.pool : Union[MPPool, None] = None
def start(self):
if self.pool is None:
self.pool = Pool(self.num_workers)
return self.pool
def wait(self):
if self.pool is not None:
self.pool.close()
self.pool.join()
self.pool = None
def terminate(self):
if self.pool is not None:
self.pool.terminate()
self.pool = None
def do(volt, paths, out_path, measType, binarize):
sel_paths: List[Path] = [dirs for dirs in paths.iterdir() if re.match(rf'^{volt}\D+', dirs.name) and dirs.is_dir()]
sel_paths.sort(key = ps.sort_key)
# extracting the unit of the folders in which images are found
unit = re.findall(r'[^0-9.]+', sel_paths[0].name)
unit = unit[0] if unit else ""
unit = unit[:-1] if unit.endswith('_') else unit
# defining the output filename
out = volt + f"{unit}.txt"
dat = ps.dt_curve(sel_paths, volt, measType, binarize)
mt = measType
bi = binarize
string = f'# point2 : {mt.point2}, point1 : {mt.point1}, DCenter : {mt.center}, Binarize : {bi.threshold},\
outline : {mt.outline}\n'
with open(out_path/out, 'w') as f:
f.write(string)
dat.to_csv(out_path/out, mode = 'a', sep = '\t', index = False)
class Worker(imageviewer.Worker):
def __init__(self, window: QMainWindow):
super().__init__(window)
self.mainwindow = window.mainwindow
# @exception_handler
def get_state(self):
while self._is_running:
if self.window.process_box.isChecked():
try:
state = {
'measType': ps.Meas_Type.from_window(self.mainwindow),
'binarize': ps.Binarize_Type.from_window(self.mainwindow)
}
except Exception as exp:
print(exp)
continue
self.state_updated.emit(state)
imageviewer.time.sleep(0.2)
else:
imageviewer.time.sleep(0.5)
@decorate_all_methods(exception_handler)
class Modvortex_ImageProcessor(imageviewer.ImageProcessor):
def __init__(self, parent: QMainWindow, worker= Worker):
self.mainwindow = parent
super().__init__(worker)
# self.measType = ps.Meas_Type.from_window(self.mainwindow)
# getting the start image from mainwindow and setting it
text = self.mainwindow.textInputFolder.toPlainText()
self.start_path = Path(text)
self.set_folder(self.start_path)
def load_images(self):
super().load_images()
if self.folders:
# changing the folder and images in the mainwindow
folder = self.folders[self.current_folder_index]
self.mainwindow.textInputFolder.setPlainText(str(folder))
self.mainwindow.load_images(self.images)
self.mainwindow.images = self.images
def closeEvent(self, event):
# resetting the folder in the folder box in mainwindow
self.mainwindow.textInputFolder.setPlainText(str(self.start_path))
self.mainwindow.load_images()
super().closeEvent(event)
@decorate_all_methods(exception_handler)
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
uic.loadUi(application_path/"mainwindow_v.ui", self)
# self.toolButton.setIconSize(iconSize)
# setting slot for the qaction
self.actionBinarizeImage.triggered.connect(self.display_binarized)
# connecting button with qaction
self.binarize_button.setAction(self.actionBinarizeImage)
# changing the binarze combobox and spinbox rebinarize the image with new values
self.b_combo_box.currentIndexChanged.connect(lambda : self.display_binarized(True)
if self.binarize_button.isChecked()
else self.display_binarized(False))
self.spinBox.valueChanged.connect(lambda : self.display_binarized(True)
if self.binarize_button.isChecked()
else self.display_binarized(False))
# disable the threshold value selection for otsu algorithm
self.b_combo_box.currentIndexChanged.connect(lambda index :
self.spinBox.setEnabled(not index)
)
self.inverse.stateChanged.connect(lambda : self.display_binarized(True) if self.binarize_button.isChecked()
else None)
self.setButton.clicked.connect(self.set_direction)
self.loadPointsButton.clicked.connect(self.def_direction)
self.dial.valueChanged.connect(self.dial_changed)
self.genEdges.clicked.connect(self.set_edge)
self.calcButton.clicked.connect(lambda : print(
ps.calculate_motion_displace(self.images, ps.Meas_Type.from_window(self),
ps.Binarize_Type.from_window(self)
)
)
)
self.calcAllButton.clicked.connect(lambda : self.calculate_all()
if self.calcAllButton.text() == "Calculate All"
else self.stop_calculate_all() )
self.bulkcalcButton.clicked.connect(self.calculate_all_from_parent)
self.loadfolder.clicked.connect(self.loadfolder_f)
self.plot_button.clicked.connect(lambda : self.plot(Path(self.textInputFolder.toPlainText()).parent/
self.save_folder.text()
))
self.dselect_button.clicked.connect(self.auto_domain_select)
self.show_domain_fit.clicked.connect(self.show_circle_fit)
self.plt_histogram_b.clicked.connect(self.plt_hist)
# Test
# self.load_options.clicked.connect(lambda : print(type(self.tabWidget.widget(0))))
# self.load_options.clicked.connect(lambda : print(self.tabWidget.widget(0).size()))
# self.load_options.clicked.connect(self.def_direction)
# load the images while clicking the load button
# self.textInputFolder.textChanged.connect(self.load_images)
self.load.clicked.connect(lambda : self.load_images()) # lambda is used bcoz signal gives\
# something to the slot which is undesirable
# when tab clicked tab closed button
self.tabWidget.tabCloseRequested.connect(self.on_tab_close_requested)
# shortcut for moving left and right across the tabs
self.tabWidget.shortcut_left = QShortcut(QKeySequence("Left"), self)
self.tabWidget.shortcut_right = QShortcut(QKeySequence("Right"), self)
self.tabWidget.shortcut_left.activated.connect(lambda : self.move_tab('left'))
self.tabWidget.shortcut_right.activated.connect(lambda : self.move_tab('right'))
self.tabWidget.currentChanged.connect(lambda : self.update_th_label())
# self.show()
self.img_viewer = None
self.settings_win = SettingWindow(self)
self.actionAbout.triggered.connect(self.show_about_dialog)
self.actionSettings.triggered.connect(self.settings_win.show)
self.actionSettings.triggered.connect(self.settings_win.activateWindow)
self.actionImage_Viewer.triggered.connect(self.open_img_viewer)
self.actionSelect_Folder.triggered.connect(self.loadfolder_f)
self.actionDocumentation.triggered.connect(self.open_docs)
# images that are loaded in the tabs
self.images = None
# save the threshold value while binarizing
self.threshold = None
# set the file filter to show only .py files
# dialog.setNameFilter("Python files (*.png)")
# poolmanager for calculating function
self.pool = PoolManager(num_workers= 4 )
# for flask api
self.flask_app = MyFlaskApp(self)
self.api_button.clicked.connect(self.toggle_api)
def show_about_dialog(self):
version = QApplication.instance().applicationVersion()
QMessageBox.about(self, "About", f"""<p>MODVORTEx<br>
(Magneto Optical Domain Velocity Observation and Real-Time Extraction)<br>
Version: {version}<br>
Written By Rakhul Raj<br>
If this program is helpful in your work, please cite our <a href="https://dx.doi.org/10.1088/1361-6501/ad8beb">article</a>.</p>""")
def open_docs(self):
QDesktopServices.openUrl(QUrl("https://github.com/RakhulR/MODVORTEx"))
def loadfolder_f(self):
# create a file dialog object
dialog = QFileDialog()
# dialog.setFileMode(QFileDialog.AnyFile)
# # set the option to show files and directories
# dialog.setOption(QFileDialog.DontUseNativeDialog, True)
# folder = dialog.getExistingDirectory(self, 'rat','' , QFileDialog.DontUseNativeDialog)
# folder.setOption(QFileDialog.ShowDirsOnly)
folder = dialog.getOpenFileName(self, "Select Directory", "", "Directory (*)")
if folder[0]:
# # adding the file to the text box.
res = Path(folder[0]).parent
self.textInputFolder.setPlainText(str(res))
def load_images(self, update_images = None):
'''
load the images to the tabs form the inputfolder if no update_images are given.
or update the images if update_images are given
Parameters
----------
update_images : list, optional
Image to update if needed. The default is None.
Returns
-------
None.
'''
# extracting the text from the textbox
# self.tabWidget.clear()
if update_images == None:
# clearing all tabs
while self.tabWidget.count():
self.tabWidget.widget(0).deleteLater()
self.tabWidget.removeTab(0)
measType = ps.Meas_Type.from_window(self)
text = self.textInputFolder.toPlainText()
path = Path(text)
image_paths = measType.settings.img_from_path(path)
# images =[* path.glob('*.png')][::1]
# images = [cv2.imread(str(image), cv2.IMREAD_GRAYSCALE)[:512] for image in images]
images = [ps.load_image(image, measType) for image in image_paths]
self.images = images
images = [self.qimage_fromdata(image) for image in images]
tabs = [MyLabel(mainwindow= self) for _ in images]
[x.set_outline(self.dial.value()) for x in tabs]
[label.resize(image.size().width(), image.size().height()) for label, image in zip(tabs,images)]
[label.setMaximumSize(image.size().width(), image.size().height()) for label, image in zip(tabs,images)]
[tab.setPixmap(QPixmap.fromImage(image))for tab, image in zip(tabs,images)]
for ii, tab in enumerate(tabs):
self.tabWidget.addTab(tab, f"img{ii}")
else :
images = [self.qimage_fromdata(image) for image in update_images]
tabs = [self.tabWidget.widget(i) for i in range(self.tabWidget.count()) if self.tabWidget.widget(i)]
[tab.setPixmap(QPixmap.fromImage(image))for tab, image in zip(tabs,images)]
def auto_domain_select(self):
binarize = ps.Binarize_Type.from_window(self)
bin_imgs = binarize.binarize_list(images= self.images)
measType = ps.Meas_Type.from_window(window = self)
measType.index = ps.Meas_Type.BUBBLE_CIRCLE_FIT
measType.select_domain = False
motions = ps.cexpand_detect(bin_imgs, measType)
# print([x.centre for x in motions])
centres = [str(x.centre).replace(' ', '') for x in motions]
# print(centres)
centres_str = ';'.join(centres)
self.select_domain_line.setText(centres_str)
def show_circle_fit(self):
binarize = ps.Binarize_Type.from_window(self)
bin_imgs = binarize.binarize_list(images= self.images)
measType = ps.Meas_Type.from_window(window = self)
measType.index = ps.Meas_Type.BUBBLE_CIRCLE_FIT
measType.select_domain = False
motions = ps.cexpand_detect(bin_imgs, measType)
shape = self.images[0].shape
new_img = ps.image_from_coords(np.array([], dtype = 'int32').reshape(0, 0),shape) # Look here
for motion in motions:
[ps.image_from_coords(domain.contour.squeeze(), shape, new_img)
for domain in motion.domains]
new_img[new_img > 0] = 255
new_img = new_img.astype(np.uint8)
new_img = cv2.cvtColor(new_img, cv2.COLOR_GRAY2BGR)
for motion in motions:
cen_rad = [cv2.minEnclosingCircle(dom.contour) for dom in motion.domains]
# print(np.diff([x[1] for x in cen_rad])*measType.settings.scale)
[cv2.circle(new_img, tuple(np.round(center).astype(int)), round(radius), ps.bd.constant.RED,1)
for center, radius in cen_rad]
tab = MyLabel(mainwindow= self)
tab.set_outline(self.dial.value()) # setting the outline value of mylabel
image = self.qimage_fromdata(new_img)
tab.resize(image.size().width(), image.size().height())
tab.setMaximumSize(image.size().width(), image.size().height())
tab.setPixmap(QPixmap.fromImage(image))
self.tabWidget.addTab(tab, 'domain_fit')
def dial_changed(self, value):
# change the label in qlabel
self.label_dial.setText(f'Width\n({value})')
# Changes the outline in the line drawn on all the custom labels
tabs = [self.tabWidget.widget(i) for i in range(self.tabWidget.count()) if self.tabWidget.widget(i)]
[tab.set_outline(value) for tab in tabs]
def update_position_label(self, x:str, y:str):
''' Updates the position of mouse in MyLabel'''
self.coord_label.setText(f"Current Coordinates (pixels): ({x}, {y})") # Update with the current coordinates
def plt_hist(self):
kernel = ps.Binarize_Type.from_window(window= self).kernel
ind = self.tabWidget.currentIndex()
if ind < len(self.images): # current tabs are image tabs
ps.plt_histogram(image= self.images[ind],threshold= self.spinBox.value(), blur_kernel= kernel )
else: # current tab is edge tab
label: QLabel = self.tabWidget.widget(ind)
pixmap: QPixmap = label.pixmap()
if pixmap:
qimage : QImage = pixmap.toImage()
image : np.ndarray = ps.qimage_to_array(qimage= qimage)
if len(image.shape) == 3:
if image.shape[2] == 3:
image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
ps.plt_histogram(image= image, blur_kernel= kernel)
elif image.shape[2] == 1:
ps.plt_histogram(image= image.squeeze(), blur_kernel= kernel)
else:
raise ValueError(f"The image format is not recognized as RBG or Grayscale. shape is {image.shape}")
elif len(image.shape) == 2:
ps.plt_histogram(image= image, blur_kernel= kernel)
else:
raise ValueError(f"The image format is not recognized as RBG or Grayscale. shape is {image.shape}")
else:
raise RuntimeError("No pixmap available in the current tab")
def update_th_label(self):
"function to set the threshold label"
if self.binarize_button.isChecked():
ind = self.tabWidget.currentIndex()
if len(self.threshold) > ind:
self.label_3.setText(f"Current Threshold Value : {self.threshold[ind]}")
else: #ind is equal to len(threshold) means that the last tab is the edge tab
self.label_3.setText("Current Threshold Value : None")
else:
self.threshold = None
self.label_3.setText("Current Threshold Value : None")
def display_binarized(self, satus):
current_index = self.tabWidget.currentIndex()
if satus:
# data_img = [self.qimage_to_numpy(image) for image in self.images]
data_img = self.images
bin_type = ps.Binarize_Type.from_window(self)
if bin_type == ps.Binarize_Type.TYPE_OTSU:
# binarized_img = [self.otsu_binarize(image) for image in data_img]
# this loop below merges the first images with the last image horizontally and take threshold and then
# seperate the image
binarized_img = []
for ii , imag in enumerate(data_img):
if ii == 0 :
imag_ext = np.concatenate((imag, data_img[-1]), axis=1, dtype=np.uint8)
ret, ch, con = self.otsu_binarize(imag_ext, bin_type)
ret = np.split(ret, [imag_ext.shape[1]//2], axis=1)[0]
ret = cv2.cvtColor(ret, cv2.COLOR_GRAY2BGR)
ret = cv2.cvtColor(ret, cv2.COLOR_BGR2GRAY)
binarized_img.append((ret, ch, con))
else:
binarized_img.append( self.otsu_binarize(imag, bin_type) )
self.threshold = [im[1] for im in binarized_img]
binarized_img = [im[0] for im in binarized_img]
self.binarized_img = binarized_img
self.update_th_label()
else:
binarized_img = [self.custom_binarize(image, bin_type
) for image in data_img]
self.threshold = [im[1] for im in binarized_img]
binarized_img = [im[0] for im in binarized_img]
self.binarized_img = binarized_img
self.update_th_label()
self.load_images(binarized_img)
del data_img, binarized_img
else:
self.binarized_img = None
self.load_images(self.images)
self.update_th_label()
self.tabWidget.setCurrentIndex(current_index)
def qimage_fromdata(self, img):
'''define a function to convert NumPy array to QImage'''
if len(img.shape) == 2: # Grayscale image
height, width = img.shape
# qimg = QImage(img.data, width, height, QImage.Format_Grayscale8) # error was happening when i crop the width of the image
qimg = QImage(bytes(img.data), width, height, QImage.Format_Grayscale8)
elif len(img.shape) == 3: # BGR image
height, width, channels = img.shape
if channels == 3:
qimg = QImage(bytes(img.data), width, height, QImage.Format_BGR888)
else:
raise ValueError("Unsupported image format")
else:
raise ValueError("Unsupported image format")
return qimg
def qimage_to_numpy(self, qimage):
'''define a function to convert QImage to NumPy array'''
width = qimage.width() # get the width of the QImage
height = qimage.height() # get the height of the QImage
# get the number of bytes per line of the QImage
bytes_per_line = qimage.bytesPerLine()
# get the raw data of the QImage as a NumPy array
image_data = qimage.bits().asarray(bytes_per_line * height)
# reshape and cast the array to match the grayscale image format
return np.reshape(image_data, (height, width)).astype(np.uint8)
# This slot will be called when the close button of a tab is pressed
def on_tab_close_requested(self,index):
self.tabWidget.widget(index).deleteLater()
self.tabWidget.removeTab(index)
def move_tab(self, direction):
'''move to the next card in the direction defined'''
current_index = self.tabWidget.currentIndex()
if direction == 'right':
next_index = (current_index + 1) % self.tabWidget.count()
self.tabWidget.setCurrentIndex(next_index)
elif direction == 'left':
next_index = (current_index - 1) % self.tabWidget.count()
self.tabWidget.setCurrentIndex(next_index)
def otsu_binarize(self, image, binarize_type: ps.Binarize_Type):
"""
take an image path as input and give binarized image, threshold image, contour as output
Parameters
----------
image : np.array
path of the image.
Returns
-------
ret : TYPE
the input image GRAY.
th : TYPE
threshold image - OTSU_Gasussian Threshold.
contour : TYPE
return the contours in the image.
"""
img = image
img_gus = cv2.GaussianBlur(img, binarize_type.kernel, 0)
if binarize_type.inverse:
th, ret = cv2.threshold(img_gus, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
else :
th, ret = cv2.threshold(img_gus, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
contour, hei = cv2.findContours(ret, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
# ret = cv2.Canny(ret, 0, 255, 7)
return (ret, th , contour)
def custom_binarize(self, image, binarize_type: ps.Binarize_Type):
"""
take an image , threshold image, contour as output
Parameters
----------
image : np.array
path of the image.
Returns
-------
ret : TYPE
the input image GRAY.
th : TYPE
threshold image - OTSU_Gasussian Threshold.
contour : TYPE
return the contours in the image.
"""
img = image
img_gus = cv2.GaussianBlur(img, binarize_type.kernel, 0)
if binarize_type.inverse:
th, ret = cv2.threshold(img_gus, binarize_type.threshold, 255, cv2.THRESH_BINARY_INV)
else :
th, ret = cv2.threshold(img_gus, binarize_type.threshold, 255, cv2.THRESH_BINARY)
contour, hei = cv2.findContours(ret, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
# ret = cv2.Canny(ret, 0, 255, 7)
return (ret, th , contour)
def def_direction(self):
tab = self.tabWidget.widget(self.tabWidget.currentIndex())
tabs = [self.tabWidget.widget(i) for i in range(self.tabWidget.count()) if self.tabWidget.widget(i)]
if tab.first_click is not None and tab.second_click is not None:
self.linep1_x.setValue(tab.first_click.x())
self.linep1_y.setValue(tab.first_click.y())
self.linep2_x.setValue(tab.second_click.x())
self.linep2_y.setValue(tab.second_click.y())
else :
self.linep1_x.setValue(0)
self.linep1_y.setValue(0)
self.linep2_x.setValue(0)
self.linep2_y.setValue(0)
def set_direction(self):
tab = self.tabWidget.widget(self.tabWidget.currentIndex())
tabs = [self.tabWidget.widget(i) for i in range(self.tabWidget.count()) if self.tabWidget.widget(i)]
# taking the points cordinates form input
p1 = QPoint(self.linep1_x.value(), self.linep1_y.value())
p2 = QPoint(self.linep2_x.value(), self.linep2_y.value())
# checking check box if it has to be set for all tabs
if not self.checkBox.isChecked():
# if any of the inputs are non zero line should be redrawn
if p1 or p2:
tab.set_line_points(p1, p2)
# if all the inputs are zero line should be deleted
else:
tab.set_line_points(None, None)
# applying the logic to all tabs if needed.
else :
if p1 or p2:
[tab.set_line_points(p1, p2) for tab in tabs]
else:
[tab.set_line_points(None, None) for tab in tabs]
def set_edge(self):
binarize = ps.Binarize_Type.from_window(self)
measType = ps.Meas_Type.from_window(window = self)
new_img = ps.get_edge(self.images, binarize, measType)
# new_img = cv2.cvtColor(new_img, cv2.COLOR_GRAY2RGB)
tab = MyLabel(mainwindow= self)
tab.set_outline(self.dial.value()) # setting the outline value of mylabel
# tab.setScaledContents(True)
# tab.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
image = self.qimage_fromdata(new_img)
tab.resize(image.size().width(), image.size().height())
tab.setMaximumSize(image.size().width(), image.size().height())
tab.setPixmap(QPixmap.fromImage(image))
# tab.setMask(QPixmap.fromImage(image).mask())
# cv2.imshow('Image 2', new_img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
# plt.imshow(new_img)
self.tabWidget.addTab(tab, 'edges')
def calculate_all(self):
paths = Path(self.textInputFolder.toPlainText()).parent
# out_path = paths/"DisplacementTime"
out_path = paths/f"{self.save_folder.text()}"
if not out_path.exists():
out_path.mkdir()
else:
# if the overwrite checkbok is not checked it will skip this directory
if not self.bulk_overwrite_check.isChecked():
QMessageBox(QMessageBox.Warning,
"Warning",
f"Specified Folder '{self.save_folder.text()}' Already Exists in the directory'{paths.name}'",
parent= self).exec()
return None
volts= ps.find_volt(paths)
arguments = dict(
measType = ps.Meas_Type.from_window(window = self),
binarize = ps.Binarize_Type.from_window(window = self)
)
do_partial = partial(do, paths = paths, out_path = out_path, **arguments)
# with Pool(4) as p:
# results = p.map(do_partial, volts)
pool = self.pool.start()
result = pool.map_async(do_partial, volts)
thread = Thread(target= self.manage_calculate_all, args=(result,))
thread.start()
# for x in volts:
# out = ps.float_str(ps.field(float(x)/10),2) + 'mT.txt'
# dat = self.dt_curve(paths, x)
# dat.to_csv(out_path/out, sep = '\t', index = False)
def manage_calculate_all(self, result):
self.calcAllButton.setText("Stop")
self.bulkcalcButton.setEnabled(False)
try:
while self.pool.pool is not None:
if result.ready():
self.pool.wait()
break
result.wait(timeout=1)
except Exception as e:
print(e)
pass
finally:
self.bulkcalcButton.setEnabled(True)
self.calcAllButton.setText("Calculate All")
def stop_calculate_all(self):
self.pool.terminate()
def calculate_all_from_parent(self):
paths_parent = Path(self.textInputFolder.toPlainText()).parent.parent
folder_name = self.save_folder.text()
arguments = dict(
measType = ps.Meas_Type.from_window(window = self),
binarize = ps.Binarize_Type.from_window(window = self)
)
iter_path = [path for path in paths_parent.iterdir()]
for paths in iter_path:
if paths.is_dir() and paths.name.endswith('mT'):
# out_path = paths/"DisplacementTime"
out_path = paths/folder_name
if not out_path.exists():
out_path.mkdir()
else:
# if the overwrite checkbok is not checked it will skip this directory
if not self.bulk_overwrite_check.isChecked():
msg_box = QMessageBox(QMessageBox.Warning,
"Warning",
f"Specified Folder '{folder_name}' Already Exists in the directory'{paths.name}'" ,
parent = self)
msg_box.setModal(False)
msg_box.setWindowFlags(msg_box.windowFlags() | Qt.WindowStaysOnTopHint)
msg_box.show()
continue
print(paths)
volts= ps.find_volt(paths)
do_partial = partial(do,paths = paths, out_path = out_path, **arguments)
with Pool(4) as p:
results = p.map(do_partial, volts)
def plot(self, path: Union[str, Path]):
'''
Plot the data in the current save folder
Parameters
----------
path : str|Path
path of the dir where the files are.
Returns
-------
None.
'''
# pattern = re.compile(r"\d+\.\d+mT\.txt")
pattern = re.compile(r'^[+-]?\d+(\.\d+)?\D+')
path = Path(path)
files = [x for x in path.iterdir() if pattern.match(x.name)]
fig, ax = plt.subplots()
# sorting the files according to the field value
files.sort(key = lambda x: float(re.match(r'^[+-]?\d+(\.\d+)?', x.name).group()))
# to read the comment character from the first file
comment_char = "#"
comments = [] # it reads all the comment lines from the file if avilable
with open(files[0], "r") as f:
for line in f:
if line.startswith(comment_char):
comments.append(line.strip())
if comments:
# we only need the comment in the first line
string= comments[0].replace('# ', '').replace(', ', '\n')
else:
mt = ps.Meas_Type.from_window(window = self)
bi = ps.Binarize_Type.from_window(window = self)
string = f'''point2 : {mt.point2}
point1 : {mt.point1}
DCenter : {mt.center}
Binarize : {bi.threshold}
outline : {mt.outline}'''
ax.text(0.25, 0.85, string, transform=ax.transAxes)
for file in files:
data = pd.read_csv(file,
sep = '\t',
comment = comment_char
)
if data.empty:
print(f"{str(file)} does not contain any data")
continue
data.plot(x = 0, y = 1 , style = 'o', label = file.name.split('.txt')[0], ax = ax)
plt.show()
def open_img_viewer(self):
# self.img_viewer_open = True
if self.img_viewer is not None:
if self.img_viewer.isVisible():
self.img_viewer.show()
self.img_viewer.activateWindow()
else:
self.img_viewer = Modvortex_ImageProcessor(parent= self,
worker= Worker)
self.img_viewer.show()
else:
self.img_viewer = Modvortex_ImageProcessor(parent= self,
worker= Worker)
self.img_viewer.show()
def toggle_api(self):
if self.flask_app.server_started:
self.stop_api()
else:
self.start_api()
def start_api(self):
self.flask_app.run_server()
self.api_button.setText('Stop API')
def stop_api(self):
if self.flask_app.server_started:
self.flask_app.close_server()
self.api_button.setText('Start API')
def closeEvent(self, event):
if self.img_viewer is not None:
if self.img_viewer.isVisible():
self.img_viewer.close()
else:
self.img_viewer = None
self.pool.terminate()
self.stop_api()
event.accept()
# def start_api(self):
# self.flask_thread = Thread(target=self.flask_app.app.run, kwargs={'debug': True, 'use_reloader': False})
# self.flask_thread.start()
# self.api_running = True
# self.api_button.setText('Stop API')
# def stop_api(self):
# if self.api_running:
# requests.post('http://127.0.0.1:5000/shutdown', json={'secret_key': self.secret_key})
# self.flask_thread.join()
# self.api_running = False
# self.api_button.setText('Start API')
class ActionButton(QPushButton):
'''An extension of a QPushButton that supports QAction.
This class represents a QPushButton extension that can be
connected to an action and that configures itself depending
on the status of the action.
When the action changes its state, the button reflects
such changes, and when the button is clicked the action
is triggered.'''
# The action associated to this button.
actionOwner = None
# Parent the widget parent of this button