-
Notifications
You must be signed in to change notification settings - Fork 1
/
StripesCounter_v11.py
executable file
·1465 lines (1272 loc) · 64.9 KB
/
StripesCounter_v11.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
#=================================================================
# Author: Patrick Brockmann CEA/DRF/LSCE - May 2022
#=================================================================
import sys, os
#======================================================
try:
import re
from PyQt5.Qt import Qt
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import matplotlib
matplotlib.use('Qt5Agg')
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
from matplotlib.transforms import Bbox
from matplotlib.collections import LineCollection
import matplotlib.patches as patches
import matplotlib.pyplot as plt
from skimage.measure import profile_line
import peakutils
import numpy as np
import cv2
from shapely.geometry import Point, LineString
import datetime
import pandas as pd
import cairo
import xml.dom.minidom
except:
print("Some modules have not been found:")
print("---> re, matplotlib, PyQt5, skimage, peakutils, numpy, cv2, shapely, cairo, xml")
sys.exit()
#======================================================
version = "v11.82"
maximumWidth = 250
#======================================================
class MainWindow(QMainWindow):
#------------------------------------------------------------------
def __init__(self):
QMainWindow.__init__(self)
self.initValues()
#-------------------------------
self.setMinimumSize(QSize(1100, 800))
self.setWindowTitle("StripesCounter " + version)
# Create new action
openAction = QAction(QIcon('open.png'), '&Open', self)
openAction.setShortcut('Ctrl+O')
openAction.setStatusTip('Open document')
openAction.triggered.connect(self.openCall)
# Create exit action
exitAction = QAction(QIcon('exit.png'), '&Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(self.exitCall)
# Create about action
aboutAction = QAction(QIcon('about.png'), '&About', self)
aboutAction.setShortcut('F1')
aboutAction.setStatusTip('About the application')
aboutAction.triggered.connect(self.aboutCall)
# Create menu bar and add action
self.menuBar = self.menuBar()
fileMenu = self.menuBar.addMenu('&File')
fileMenu.addAction(openAction)
fileMenu.addAction(exitAction)
fileMenu = self.menuBar.addMenu('&About')
fileMenu.addAction(aboutAction)
self.cboxInverseImage = QCheckBox("Inverse image")
self.cboxInverseImage.setChecked(False)
self.cboxInverseImage.toggled.connect(self.toggled_cboxInverseImage)
self.labelAlpha = QLabel("Contrast level: 1.0")
self.labelAlpha.setAlignment(Qt.AlignLeft)
self.labelBeta = QLabel("Brightness level: 0")
self.labelBeta.setAlignment(Qt.AlignLeft)
self.labelKernelSize = QLabel("Kernel size: " + str(self.kernelSize))
self.labelKernelSize.setAlignment(Qt.AlignLeft)
self.labelProfileLinewidth = QLabel("Profile linewidth: " + str(self.profileLinewidth))
self.labelProfileLinewidth.setAlignment(Qt.AlignLeft)
self.labelPeakUtils_minDist = QLabel("PeakUtils - Minimum distance: " + str(self.peakutils_minDist))
self.labelPeakUtils_minDist.setAlignment(Qt.AlignLeft)
self.labelPeakUtils_thres = QLabel("PeakUtils - Threshold: %d" % self.peakutils_thres)
self.labelPeakUtils_thres.setAlignment(Qt.AlignLeft)
self.mySliderAlpha = QSlider(Qt.Horizontal, self)
self.mySliderAlpha.setMaximumWidth(maximumWidth)
self.mySliderAlpha.setMinimum(10)
self.mySliderAlpha.setMaximum(30)
self.mySliderAlpha.setValue(1)
self.mySliderAlpha.setTickInterval(1)
self.mySliderAlpha.setTickPosition(QSlider.TicksBelow)
self.mySliderAlpha.valueChanged[int].connect(self.changeValueAlpha)
self.mySliderBeta = QSlider(Qt.Horizontal, self)
self.mySliderBeta.setMaximumWidth(maximumWidth)
self.mySliderBeta.setMinimum(-100)
self.mySliderBeta.setMaximum(100)
self.mySliderBeta.setValue(0)
self.mySliderBeta.setTickInterval(5)
self.mySliderBeta.setTickPosition(QSlider.TicksBelow)
self.mySliderBeta.valueChanged[int].connect(self.changeValueBeta)
self.mySliderKernelSize = QSlider(Qt.Horizontal, self)
self.mySliderKernelSize.setMaximumWidth(maximumWidth)
self.mySliderKernelSize.setMinimum(1)
self.mySliderKernelSize.setMaximum(51)
self.mySliderKernelSize.setValue(self.kernelSize)
self.mySliderKernelSize.setTickInterval(2)
self.mySliderKernelSize.setSingleStep(2)
self.mySliderKernelSize.setTickPosition(QSlider.TicksBelow)
self.mySliderKernelSize.valueChanged[int].connect(self.changeValueKernelSize)
self.mySliderProfileLinewidth = QSlider(Qt.Horizontal, self)
self.mySliderProfileLinewidth.setMaximumWidth(maximumWidth)
self.mySliderProfileLinewidth.setMinimum(1)
self.mySliderProfileLinewidth.setMaximum(50)
self.mySliderProfileLinewidth.setValue(self.profileLinewidth)
self.mySliderProfileLinewidth.setTickInterval(1)
self.mySliderProfileLinewidth.setTickPosition(QSlider.TicksBelow)
self.mySliderProfileLinewidth.valueChanged[int].connect(self.changeValueProfileLinewidth)
self.mySliderPeakUtils_minDist = QSlider(Qt.Horizontal, self)
self.mySliderPeakUtils_minDist.setMaximumWidth(maximumWidth)
self.mySliderPeakUtils_minDist.setMinimum(1)
self.mySliderPeakUtils_minDist.setMaximum(30)
self.mySliderPeakUtils_minDist.setValue(self.peakutils_minDist)
self.mySliderPeakUtils_minDist.setTickInterval(1)
self.mySliderPeakUtils_minDist.setTickPosition(QSlider.TicksBelow)
self.mySliderPeakUtils_minDist.valueChanged[int].connect(self.changeValuePeakUtils_minDist)
self.mySliderPeakUtils_thres = QSlider(Qt.Horizontal, self)
self.mySliderPeakUtils_thres.setMaximumWidth(maximumWidth)
self.mySliderPeakUtils_thres.setMinimum(0)
self.mySliderPeakUtils_thres.setMaximum(255)
self.mySliderPeakUtils_thres.setValue(self.peakutils_thres)
self.mySliderPeakUtils_thres.setTickInterval(5)
self.mySliderPeakUtils_thres.setTickPosition(QSlider.TicksBelow)
self.mySliderPeakUtils_thres.valueChanged[int].connect(self.changeValuePeakUtils_thres)
self.cboxPeaks = QCheckBox("Display peaks on current segment")
self.cboxPeaks.setChecked(False)
self.cboxPeaks.toggled.connect(self.toggled_cboxPeaks)
self.cboxReverseProfile = QCheckBox("Reverse profile")
self.cboxReverseProfile.setChecked(False)
self.cboxReverseProfile.toggled.connect(self.toggled_cboxReverseProfile)
#-----------------------
self.fig = plt.figure(figsize=(8,8))
self.ax0 = self.fig.add_axes([0.06, 0.40, 0.90, 0.52]) # [left, bottom, width, height]
self.ax1 = self.fig.add_axes([0.06, 0.12, 0.90, 0.22])
self.canvas = FigureCanvas(self.fig)
# https://github.com/matplotlib/matplotlib/issues/707/
self.canvas.setFocusPolicy(Qt.ClickFocus)
self.canvas.setFocus()
self.canvas.mpl_connect('button_press_event', self.on_press)
self.canvas.mpl_connect('button_release_event', self.on_release)
self.canvas.mpl_connect('pick_event', self.on_pick)
self.canvas.mpl_connect('motion_notify_event', self.on_motion)
self.canvas.mpl_connect('scroll_event', self.zoom)
#-----------------------
self.buttonDefineScaleValue = QPushButton('Define scale value')
self.buttonDefineScaleValue.setMaximumWidth(maximumWidth)
self.buttonDefineScaleValue.clicked.connect(self.defineScaleValue)
self.buttonDefineScaleLength = QPushButton('Define scale length')
self.buttonDefineScaleLength.setMaximumWidth(maximumWidth)
self.buttonDefineScaleLength.clicked.connect(self.defineScaleLength)
self.buttonDefineScale = QPushButton('Define scale')
self.buttonDefineScale.setMaximumWidth(maximumWidth)
self.buttonDefineScale.clicked.connect(self.defineScale)
self.buttonExtract = QPushButton('Extract peaks from profile')
self.buttonExtract.setMaximumWidth(maximumWidth)
self.buttonExtract.clicked.connect(self.extract)
self.buttonLoad = QPushButton('Load segments and peaks')
self.buttonLoad.setMaximumWidth(maximumWidth)
self.buttonLoad.clicked.connect(self.load)
self.buttonSave = QPushButton('Save segments and peaks')
self.buttonSave.setMaximumWidth(maximumWidth)
self.buttonSave.clicked.connect(self.save)
self.buttonCapture = QPushButton('Capture displayed image')
self.buttonCapture.setMaximumWidth(maximumWidth)
self.buttonCapture.clicked.connect(self.capture)
self.buttonDeleteLastSegment = QPushButton('Delete last segment')
self.buttonDeleteLastSegment.setMaximumWidth(maximumWidth)
self.buttonDeleteLastSegment.clicked.connect(self.deleteLastSegment)
self.buttonSaveFullImage = QPushButton('Save image with segments and peaks')
self.buttonSaveFullImage.setMaximumWidth(maximumWidth)
self.buttonSaveFullImage.clicked.connect(self.saveFullImageSVG)
layoutH = QHBoxLayout()
layoutV1 = QVBoxLayout()
layoutV1.addWidget(self.canvas)
layoutV2 = QVBoxLayout()
layoutV2.setAlignment(Qt.AlignTop)
layoutV2.addWidget(self.cboxInverseImage)
layoutV2.addSpacing(1)
layoutV2.addWidget(self.labelAlpha)
layoutV2.addWidget(self.mySliderAlpha)
layoutV2.addSpacing(1)
layoutV2.addWidget(self.labelBeta)
layoutV2.addWidget(self.mySliderBeta)
layoutV2.addSpacing(1)
layoutV2.addWidget(self.labelKernelSize)
layoutV2.addWidget(self.mySliderKernelSize)
layoutV2.addSpacing(1)
layoutV2.addWidget(self.labelProfileLinewidth)
layoutV2.addWidget(self.mySliderProfileLinewidth)
layoutV2.addSpacing(1)
layoutV2.addWidget(self.labelPeakUtils_minDist)
layoutV2.addWidget(self.mySliderPeakUtils_minDist)
layoutV2.addSpacing(1)
layoutV2.addWidget(self.labelPeakUtils_thres)
layoutV2.addWidget(self.mySliderPeakUtils_thres)
layoutV2.addWidget(self.cboxPeaks)
layoutV2.addWidget(self.cboxReverseProfile)
layoutV2.addSpacing(1)
layoutV2.addWidget(self.buttonDefineScaleValue)
layoutV2.addWidget(self.buttonDefineScaleLength)
layoutV2.addWidget(self.buttonDefineScale)
layoutV2.addSpacing(20)
layoutV2.addWidget(self.buttonExtract)
layoutV2.addWidget(self.buttonLoad)
layoutV2.addWidget(self.buttonSave)
layoutV2.addSpacing(20)
layoutV2.addWidget(self.buttonCapture)
layoutV2.addSpacing(20)
layoutV2.addWidget(self.buttonDeleteLastSegment)
layoutV2.addSpacing(20)
layoutV2.addWidget(self.buttonSaveFullImage)
layoutH.addLayout(layoutV1)
layoutH.addLayout(layoutV2)
#layoutH.addStretch(1)
# Create a placeholder widget to hold our toolbar and canvas.
widget = QWidget()
widget.setLayout(layoutH)
self.setCentralWidget(widget)
self.initInterface()
#------------------------------------------------------------------
def initValues(self):
self.alpha_default = 0.3
self.line_object = None
self.scale_object = None
self.scaleValue_object = None
self.scaleValue = 0.
self.scaleLength = 0
self.offset = [0,0]
self.n = 0
self.mousepress = None
self.listLabelPoints = []
self.current_artist = None
self.press = False
self.xpress = 0
self.ypress = 0
self.cur_xlim = 0
self.cur_ylim = 0
self.shift_is_held = False
self.kernelSize = 3
self.kernelOffset = 0
self.profileLinewidth = 1
self.peakutils_minDist = 1
self.peakutils_thres = 125
self.lineWithWidth = None
self.dist_profile = None
self.profile = None
self.profile_convolved = None
self.indexes = None
self.peaksCurve = None
self.peaks = None
self.peakOver0 = None
self.peakOver1 = None
self.segmentNumb = 0
self.segmentList = []
self.segmentTextList = []
self.peaksExtractedList = []
self.peakExtractedOver0 = None
self.peaksExtracted1 = None
self.peakExtractedOver1 = None
self.ticksCollectionList = []
self.tickOver = None
self.line1 = self.line2 = self.line3 = None
self.counterFilename = 1
self.radius = 25
#------------------------------------------------------------------
def initInterface(self):
self.cboxInverseImage.setChecked(False)
self.cboxInverseImage.setEnabled(False)
self.labelAlpha.setEnabled(False)
self.mySliderAlpha.setEnabled(False)
self.labelBeta.setEnabled(False)
self.mySliderBeta.setEnabled(False)
self.labelKernelSize.setEnabled(False)
self.mySliderKernelSize.setEnabled(False)
self.labelProfileLinewidth.setEnabled(False)
self.mySliderProfileLinewidth.setEnabled(False)
self.labelPeakUtils_thres.setEnabled(False)
self.mySliderPeakUtils_thres.setEnabled(False)
self.labelPeakUtils_minDist.setEnabled(False)
self.cboxPeaks.setEnabled(False)
self.cboxReverseProfile.setEnabled(False)
self.mySliderPeakUtils_minDist.setEnabled(False)
self.cboxPeaks.setChecked(False)
self.cboxReverseProfile.setChecked(False)
self.buttonDefineScale.setEnabled(False)
self.buttonDefineScaleValue.setEnabled(False)
self.buttonDefineScaleLength.setEnabled(False)
self.buttonCapture.setEnabled(False)
self.buttonExtract.setEnabled(False)
self.buttonSave.setEnabled(False)
self.buttonLoad.setEnabled(False)
self.buttonDeleteLastSegment.setEnabled(False)
self.buttonSaveFullImage.setEnabled(False)
self.mySliderKernelSize.setValue(self.kernelSize)
self.mySliderProfileLinewidth.setValue(self.profileLinewidth)
self.mySliderPeakUtils_minDist.setValue(self.peakutils_minDist)
self.mySliderPeakUtils_thres.setValue(self.peakutils_thres)
self.ax0.set_visible(False)
self.ax1.set_visible(False)
#------------------------------------------------------------------
def changeValueAlpha(self, value):
self.alphaLevel = value/10.
self.labelAlpha.setText("Contrast level: " + str(self.alphaLevel))
self.adjusted = cv2.convertScaleAbs(self.gray, alpha=self.alphaLevel, beta=self.betaLevel)
self.image_object.set_data(self.adjusted)
self.drawProfile(resetAxis=False)
self.canvas.draw()
#------------------------------------------------------------------
def toggled_cboxInverseImage(self):
self.gray = cv2.bitwise_not(self.gray)
self.adjusted = cv2.convertScaleAbs(self.gray, alpha=self.alphaLevel, beta=self.betaLevel)
self.image_object.set_data(self.adjusted)
self.drawProfile(resetAxis=False)
self.canvas.draw()
#------------------------------------------------------------------
def changeValueBeta(self, value):
self.betaLevel = value
self.labelBeta.setText("Brighness level: " + str(self.betaLevel))
self.adjusted = cv2.convertScaleAbs(self.gray, alpha=self.alphaLevel, beta=self.betaLevel)
self.image_object.set_data(self.adjusted)
self.drawProfile(resetAxis=False)
self.canvas.draw()
#------------------------------------------------------------------
def changeValueKernelSize(self, value):
if value % 2 != 0:
self.kernelSize = value
self.labelKernelSize.setText("Kernel size: " + str(self.kernelSize))
self.drawProfile(resetAxis=False)
#------------------------------------------------------------------
def changeValueProfileLinewidth(self, value):
self.profileLinewidth= value
self.labelProfileLinewidth.setText("Profile linewidth: " + str(self.profileLinewidth))
self.update_lineWithWidth()
self.canvas.draw()
self.drawProfile(resetAxis=False)
#------------------------------------------------------------------
def changeValuePeakUtils_minDist(self, value):
self.peakutils_minDist = value
self.labelPeakUtils_minDist.setText("PeakUtils - Minimum distance: " + str(self.peakutils_minDist))
self.drawProfile(resetAxis=False)
#------------------------------------------------------------------
def changeValuePeakUtils_thres(self, value):
self.peakutils_thres = value
self.labelPeakUtils_thres.setText("PeakUtils - Threshold: %d" % self.peakutils_thres)
self.drawProfile(resetAxis=False)
#------------------------------------------------------------------
def toggled_cboxPeaks(self):
self.drawProfile(resetAxis=False)
#------------------------------------------------------------------
def toggled_cboxReverseProfile(self):
self.drawProfile(resetAxis=False)
#------------------------------------------------------------------
def zoom(self, event):
try:
# https://stackoverflow.com/questions/11551049/matplotlib-plot-zooming-with-scroll-wheel
scale_zoom = 1.2
cur_xlim = event.inaxes.get_xlim()
cur_ylim = event.inaxes.get_ylim()
xdata = event.xdata # get event x location
ydata = event.ydata # get event y location
if event.button == 'up':
# deal with zoom in
scale_factor = 1 / scale_zoom
elif event.button == 'down':
# deal with zoom out
scale_factor = scale_zoom
else:
# deal with something that should never happen
scale_factor = 1
#print(event.button)
new_width = (cur_xlim[1] - cur_xlim[0]) * scale_factor
new_height = (cur_ylim[1] - cur_ylim[0]) * scale_factor
relx = (cur_xlim[1] - xdata)/(cur_xlim[1] - cur_xlim[0])
rely = (cur_ylim[1] - ydata)/(cur_ylim[1] - cur_ylim[0])
event.inaxes.set_xlim([xdata - new_width * (1-relx), xdata + new_width * (relx)])
event.inaxes.set_ylim([ydata - new_height * (1-rely), ydata + new_height * (rely)])
self.canvas.draw()
except:
return
#------------------------------------------------------------------
def on_release(self, event):
if event.key == 'shift':
self.shift_is_held = False
self.current_artist = None
self.press = False
if self.line_object != None:
self.line_object.set_alpha(self.alpha_default)
for p in list(self.ax0.patches):
p.set_alpha(self.alpha_default)
self.canvas.draw()
#------------------------------------------------------------------
def on_pick(self, event):
if event.mouseevent.button == 3:
self.mousepress = "right"
elif event.mouseevent.button == 1:
self.mousepress = "left"
# https://stackoverflow.com/questions/29086662/matplotlib-pick-event-functionality
# filter because the scroll wheel is registered as a button
if event.mouseevent.button == 'down' or event.mouseevent.button == 'up':
#print("pick", event.mouseevent.button)
return
if self.current_artist is None:
self.current_artist = event.artist
label = event.artist.get_label()
#print("pick", label)
if label == "Profile":
xdata = event.artist.get_xdata()
ydata = event.artist.get_ydata()
x1, y1 = event.mouseevent.xdata, event.mouseevent.ydata
self.offset = xdata[0] - x1, ydata[0] - y1
event.artist.set_alpha(1.0)
self.canvas.draw()
elif label.startswith('Point'):
x0, y0 = self.current_artist.center
x1, y1 = event.mouseevent.xdata, event.mouseevent.ydata
self.offset = [(x0 - x1), (y0 - y1)]
event.artist.set_alpha(1.0)
self.canvas.draw()
#------------------------------------------------------------------
def clearPeaksOver(self):
if self.peakOver0 != None:
self.peakOver0.remove()
self.peakOver0 = None
if self.peakOver1 != None:
self.peakOver1.remove()
self.peakOver1 = None
if self.peakExtractedOver0 != None:
self.peakExtractedOver0.remove()
self.peakExtractedOver0 = None
if self.peakExtractedOver1 != None:
self.peakExtractedOver1.remove()
self.peakExtractedOver1 = None
if self.tickOver != None:
self.tickOver.remove()
self.tickOver = None
self.canvas.draw()
#------------------------------------------------------------------
def on_motion(self, event):
self.clearPeaksOver()
# display over scatter points when mouse passes over a peak
cont = False
if event.inaxes == self.ax0 and self.peaks != None and self.cboxPeaks.isChecked():
cont, ind = self.peaks.contains(event)
elif event.inaxes == self.ax1 and self.peaksCurve != None:
cont, ind = self.peaksCurve.contains(event)
if cont and self.peaks != None:
i = ind["ind"][0]
pos = self.peaks.get_offsets()[i]
self.peakOver0 = self.ax0.scatter(pos[0], pos[1],
c='yellow', s=10, zorder=12)
pos = self.peaksCurve.get_offsets()[i]
self.peakOver1 = self.ax1.scatter(pos[0], pos[1],
c='yellow', s=200, edgecolors='b', lw=1, alpha=0.8, zorder=0)
self.canvas.draw()
#----------------------------------------------
if event.inaxes == self.ax0 and len(self.peaksExtractedList) != 0 and self.line_object == None:
offset = 0
for n, peaksExtracted in enumerate(self.peaksExtractedList):
cont, ind = peaksExtracted.contains(event)
if cont:
i = ind["ind"][0]
pos = peaksExtracted.get_offsets()[i]
self.peakExtractedOver0 = self.ax0.scatter(pos[0], pos[1], marker='o',
c='yellow', s=10, zorder=12)
pos = self.peaksExtracted1.get_offsets()[i+offset]
self.peakExtractedOver1 = self.ax1.scatter(pos[0], pos[1],
c='yellow', s=200, edgecolors='b', lw=1, alpha=0.8, zorder=0)
break
offset = offset + len(peaksExtracted.get_offsets())
self.canvas.draw()
#----------------------------------------------
if event.inaxes == self.ax1 and len(self.peaksExtractedList) != 0 and self.line_object == None:
cont, ind = self.peaksExtracted1.contains(event)
if cont:
i = ind["ind"][0]
pos = self.peaksExtracted1.get_offsets()[i]
self.peakExtractedOver1 = self.ax1.scatter(pos[0], pos[1], marker='o',
c='yellow', s=200, edgecolors='b', lw=1, alpha=0.8, zorder=0)
peaksExtractedAllList = [sc.get_offsets() for sc in self.peaksExtractedList] # all peaks as a unique list
peaksExtractedAll = np.concatenate(peaksExtractedAllList)
self.peakExtractedOver0 = self.ax0.scatter(peaksExtractedAll[i][0], peaksExtractedAll[i][1], marker='o',
c='yellow', s=10, zorder=12)
self.canvas.draw()
#----------------------------------------------
if not self.press: return
if event.xdata == None or event.ydata == None: return
#----------------------------------------------
if self.current_artist != None:
label = self.current_artist.get_label()
dx, dy = self.offset
if label == "Profile":
xdata = list(self.line_object.get_xdata())
ydata = list(self.line_object.get_ydata())
xdata0 = xdata[0]
ydata0 = ydata[0]
for i in range(0,len(xdata)):
xdata[i] = event.xdata + dx + xdata[i] - xdata0
ydata[i] = event.ydata + dy + ydata[i] - ydata0
self.line_object.set_data(xdata, ydata)
for p in list(self.ax0.patches):
pointLabel = p.get_label()
i = self.listLabelPoints.index(pointLabel)
p.center = xdata[i], ydata[i]
elif label.startswith('Point'):
cx, cy = event.xdata + dx, event.ydata + dy
self.current_artist.center = cx, cy
xdata = list(self.line_object.get_xdata())
ydata = list(self.line_object.get_ydata())
for i in range(0,len(xdata)):
if self.listLabelPoints[i] == label:
xdata[i] = cx
ydata[i] = cy
break
self.line_object.set_data(xdata, ydata)
self.update_lineWithWidth()
self.canvas.draw()
self.drawProfile(resetAxis=True)
elif event.inaxes == self.ax0 or event.inaxes == self.ax1:
dx = event.xdata - self.xpress
dy = event.ydata - self.ypress
self.cur_xlim -= dx
self.cur_ylim -= dy
event.inaxes.set_xlim(self.cur_xlim)
event.inaxes.set_ylim(self.cur_ylim)
self.canvas.draw()
#------------------------------------------------------------------
def on_press(self, event):
self.clearPeaksOver()
self.press = True
if event.button == 3:
self.mousepress = "right"
elif event.button == 1:
self.mousepress = "left"
if event.key == 'shift':
self.shift_is_held = True
if event.inaxes == self.ax0 or event.inaxes == self.ax1:
self.cur_xlim = event.inaxes.get_xlim()
self.cur_ylim = event.inaxes.get_ylim()
self.xpress = event.xdata
self.ypress = event.ydata
if event and event.dblclick and self.shift_is_held:
if len(self.listLabelPoints) < 2:
self.n = self.n+1
x, y = event.xdata, event.ydata
newPointLabel = "Point%d"%self.n
point_object = patches.Circle([x, y], radius=self.radius, color='red', fill=False, lw=2,
alpha=self.alpha_default, transform=self.ax0.transData, label=newPointLabel)
point_object.set_picker(5)
self.ax0.add_patch(point_object)
self.listLabelPoints.append(newPointLabel)
if len(self.listLabelPoints) == 2:
xdata = []
ydata = []
for p in list(self.ax0.patches):
cx, cy = p.center
xdata.append(cx)
ydata.append(cy)
self.line_object, = self.ax0.plot(xdata, ydata, alpha=self.alpha_default, c='red', lw=2,
picker=True, pickradius=5, label="Profile")
self.update_lineWithWidth()
self.canvas.draw()
self.drawProfile(resetAxis=True)
#----------------------------------------------
if event.inaxes == self.ax0 and len(self.segmentList) != 0 and self.line_object == None:
for n, segment in enumerate(self.segmentList):
cont, ind = segment.contains(event)
if cont:
if self.mousepress == "left":
xdata = list(segment.get_xdata())
ydata = list(segment.get_ydata())
line = LineString([(xdata[0], ydata[0]), (xdata[1], ydata[1])])
point = Point(event.xdata, event.ydata)
# Closest point on the line
newPoint = line.interpolate(line.project(point))
posPeaks = self.peaksExtractedList[n].get_offsets()
newPosPeaks = np.concatenate([posPeaks, np.array(newPoint.coords, ndmin=2)])
# Ticks
tick = self.drawTicks(line, [newPoint.coords[0][0]], [newPoint.coords[0][1]])
ticks = self.ticksCollectionList[n].get_segments()
ticks.append(tick[0])
# sort peaks along the segment after peak add
posDistance = []
for p in newPosPeaks:
distance = Point(xdata[0], ydata[0]).distance(Point(p))
posDistance.append(distance)
sortIndices = np.argsort(posDistance)
newPosPeaks = newPosPeaks[sortIndices]
self.peaksExtractedList[n].set_offsets(newPosPeaks)
newTicks = np.array(ticks)[sortIndices]
self.ticksCollectionList[n].set_segments(newTicks)
self.canvas.draw()
self.update_peaksExtractedPlot(resetAxis=False)
break
#----------------------------------------------
if event.inaxes == self.ax0 and len(self.peaksExtractedList) != 0 and self.line_object == None:
for n, peaksExtracted in enumerate(self.peaksExtractedList):
cont, ind = peaksExtracted.contains(event)
if cont:
if self.mousepress == "right":
i = ind["ind"][0]
posPeaks = peaksExtracted.get_offsets()
ticks = self.ticksCollectionList[n].get_segments()
if len(posPeaks) > 2:
newPosPeaks = np.delete(posPeaks, i, axis=0)
self.peaksExtractedList[n].set_offsets(newPosPeaks)
del ticks[i]
self.ticksCollectionList[n].set_segments(ticks)
self.canvas.draw()
self.update_peaksExtractedPlot(resetAxis=False)
break
#------------------------------------------------------------------
def defineScalePixel(self):
if self.scaleValue != 0. and self.scaleLength != 0:
self.scalePixel = self.scaleValue / self.scaleLength
else:
self.scalePixel = 1
#------------------------------------------------------------------
def drawProfile(self, resetAxis=False):
if self.line_object is None:
return
self.defineScalePixel()
try:
xdata = list(self.line_object.get_xdata())
ydata = list(self.line_object.get_ydata())
self.profile = np.array([])
self.profile_mx = np.array([])
self.profile_my = np.array([])
self.dist_profile = np.array([])
self.profile = profile_line(self.adjusted, (ydata[0], xdata[0]), (ydata[1], xdata[1]),
order=0, mode='constant', cval=0, linewidth=self.profileLinewidth)
self.profile_mx = profile_line(self.mx, (ydata[0], xdata[0]), (ydata[1], xdata[1]),
order=0, mode='constant', cval=0, linewidth=self.profileLinewidth)
self.profile_my = profile_line(self.my, (ydata[0], xdata[0]), (ydata[1], xdata[1]),
order=0, mode='constant', cval=0, linewidth=self.profileLinewidth)
self.dist_profile = np.linspace(0, self.scalePixel*len(self.profile), num=len(self.profile))
if not resetAxis:
xlim = self.ax1.get_xlim()
ylim = self.ax1.get_ylim()
self.ax1.clear()
self.ax1.set_facecolor('whitesmoke')
self.ax1.set_visible(True)
if self.cboxReverseProfile.isChecked():
self.profile = 255 - self.profile
self.ax1.plot(self.dist_profile, self.profile, c='red', lw=1, alpha=0.8)
self.ax1.axvline(x=0, linestyle='dashed', color='gray', alpha=0.8)
self.ax1.axvline(x=self.dist_profile[-1], linestyle='dashed', color='gray', alpha=0.8)
kernel = np.ones(self.kernelSize) / self.kernelSize
self.kernelOffset = int(self.kernelSize/2)
# use mode='same' and put boundaries values to np.nan
self.profile_convolved = np.convolve(self.profile, kernel, mode='same')
self.profile_convolved[0:self.kernelOffset] = self.profile_convolved[-self.kernelOffset:] = np.nan
self.ax1.plot(self.dist_profile, self.profile_convolved, c='b', lw=1, alpha=0.8)
# https://peakutils.readthedocs.io/en/latest/reference.html
self.indexes = peakutils.indexes(self.profile_convolved, thres=self.peakutils_thres, thres_abs=True, min_dist=self.peakutils_minDist)
self.peaksCurve = self.ax1.scatter(self.dist_profile[self.indexes], self.profile_convolved[self.indexes], c='b', s=10)
if self.peaks != None:
self.peaks.remove()
self.peaks = None
if self.cboxPeaks.isChecked():
line = LineString([(xdata[0], ydata[0]), (xdata[1], ydata[1])])
points = []
for i in self.indexes:
point = Point(self.profile_mx[i], self.profile_my[i])
# Closest point on the line
newPoint = line.interpolate(line.project(point))
points.append(newPoint)
xs = [point.x for point in points]
ys = [point.y for point in points]
self.peaks = self.ax0.scatter(xs, ys, c='b', s=5, zorder=10)
peaksNb = len(self.indexes)
self.line1 = "Number of peaks: %3d" %(peaksNb)
if peaksNb > 1:
stripesDist = self.dist_profile[self.indexes[-1]]-self.dist_profile[self.indexes[0]]
self.line2 = "Length of stripes: %.5f (first: %.5f, last: %.5f)" \
%(stripesDist, self.dist_profile[self.indexes[0]], self.dist_profile[self.indexes[-1]])
self.line3 = "Growth stripe rate (mm/stripe): %.5f" %(stripesDist/(peaksNb-1))
self.ax1.set_title(self.line1 + '\n' + self.line2 + '\n' + self.line3, y=-0.55, loc='left', fontsize=10)
else:
self.ax1.set_title(self.line1 + '\n\n', y=-0.55, loc='left', fontsize=10)
self.ax1.grid(linestyle='dotted')
self.ax1.axhline(self.peakutils_thres, color="b", lw=1, linestyle='solid', alpha=0.8)
self.ax1.yaxis.set_visible(True)
if not resetAxis:
self.ax1.set_xlim(xlim)
self.ax1.set_ylim(ylim)
self.labelKernelSize.setEnabled(True)
self.mySliderKernelSize.setEnabled(True)
self.labelProfileLinewidth.setEnabled(True)
self.mySliderProfileLinewidth.setEnabled(True)
self.labelPeakUtils_minDist.setEnabled(True)
self.mySliderPeakUtils_minDist.setEnabled(True)
self.labelPeakUtils_thres.setEnabled(True)
self.mySliderPeakUtils_thres.setEnabled(True)
self.cboxPeaks.setEnabled(True)
self.cboxReverseProfile.setEnabled(True)
self.buttonDefineScaleValue.setEnabled(True)
self.buttonDefineScaleLength.setEnabled(True)
self.buttonDefineScale.setEnabled(True)
self.buttonExtract.setEnabled(True)
self.canvas.draw()
except:
#print("Error in drawProfile")
return
#------------------------------------------------------------------
def drawTicks(self, line, x, y, length=5):
left = line.parallel_offset(length, 'left')
right = line.parallel_offset(length, 'right')
ticks = []
for i in range(len(x)):
p = Point(x[i],y[i])
a = left.interpolate(line.project(p))
b = right.interpolate(line.project(p))
ticks.append(LineString([a, p, b]).coords) # keep p point to sort from distance later
return ticks
#------------------------------------------------------------------
def openCall(self):
self.openFileNameDialog()
#------------------------------------------------------------------
def detectScale(self):
try:
fld = cv2.ximgproc.createFastLineDetector()
lines = fld.detect(self.mask)
self.scaleLength = 0
for line in lines:
pt1 = np.array((line[0][0],line[0][1]))
pt2 = np.array((line[0][2],line[0][3]))
length = np.linalg.norm(pt1 - pt2)
#print(pt1, pt2, dist)
if (length > self.scaleLength):
self.scaleLength = int(length)
point1Scale = pt1
point2Scale = pt2
#print("Detected scale length in pixel: ", scaleLength)
if self.scaleLength > 0:
self.scale_object, = self.ax0.plot([point1Scale[0], point2Scale[0]],
[point1Scale[1], point2Scale[1]],
alpha=1.0, c='purple', lw=2)
except:
self.scaleLength = 0
try:
self.scaleValue_object = self.ax0.text(
min(point1Scale[0], point2Scale[0]),
min(point1Scale[1], point2Scale[1]),
" %.3f mm" %(self.scaleValue),
alpha=1.0, c='purple', horizontalalignment='left', verticalalignment='bottom', clip_on=True)
except:
self.scaleValue_object = self.ax0.text(
200, 200, # Set a default scaleValue_object at 200,200
" %.3f mm" %(self.scaleValue),
alpha=1.0, c='purple', horizontalalignment='left', verticalalignment='bottom', clip_on=True)
try:
import pytesseract
scaleDetected = pytesseract.image_to_string(self.mask)
matchObj = re.match(r'[^0-9]*([0-9]*)mm', scaleDetected.strip())
self.scaleValue = float(matchObj.group(1))
#print("Detected scale value: ", self.scaleValue)
self.scaleValue_object.set_text(" %.3f mm" %(self.scaleValue))
except:
self.scaleValue = 0.
#------------------------------------------------------------------
def defineScaleValue(self):
dialog = QInputDialog()
dialog.setInputMode(QInputDialog.DoubleInput)
dialog.setLocale(QLocale(QLocale.English, QLocale.UnitedStates))
dialog.setLabelText("Value: ")
dialog.setDoubleMinimum(0)
dialog.setDoubleMaximum(100)
dialog.setIntStep(1)
dialog.setDoubleDecimals(3)
dialog.setDoubleValue(self.scaleValue)
dialog.setWindowTitle("Get scale value")
okPressed = dialog.exec_()
if okPressed:
self.scaleValue = dialog.doubleValue()
else:
return
self.ax0.set_title(os.path.basename(self.imageFileName) + '\n'
+ " Scale length [pixels]: %s" %(self.scaleLength) + '\n'
+ " Scale value [mm]: %.3f" %(self.scaleValue),
loc='left', fontsize=10)
self.scaleValue_object.set_text(" %.3f mm" %(self.scaleValue))
self.drawProfile(resetAxis=True)
#------------------------------------------------------------------
def defineScaleLength(self):
dialog = QInputDialog()
dialog.setInputMode(QInputDialog.DoubleInput)
dialog.setLocale(QLocale(QLocale.English, QLocale.UnitedStates))
dialog.setLabelText("Length: ")
dialog.setDoubleMinimum(0)
dialog.setDoubleMaximum(10000)
dialog.setIntStep(1)
dialog.setDoubleDecimals(0)
dialog.setDoubleValue(self.scaleLength)
dialog.setWindowTitle("Get scale length")
okPressed = dialog.exec_()
if okPressed:
self.scaleLength = dialog.doubleValue()
else:
return
if self.scale_object != None:
self.scale_object.remove()
self.scale_object = None
self.ax0.set_title(os.path.basename(self.imageFileName) + '\n'
+ " Scale length [pixels]: %s" %(self.scaleLength) + '\n'
+ " Scale value [mm]: %.3f" %(self.scaleValue),
loc='left', fontsize=10)
self.scaleValue_object.set_text(" %.3f mm" %(self.scaleValue))
self.drawProfile(resetAxis=True)
#------------------------------------------------------------------
def defineScale(self):
xdata = self.line_object.get_xdata()
ydata = self.line_object.get_ydata()
point1Scale = [xdata[0], ydata[0]] # Scale from the 1st segment
point2Scale = [xdata[1], ydata[1]]
self.scaleLength = int(np.linalg.norm(np.array(point1Scale) - np.array(point2Scale)))
self.ax0.set_title(os.path.basename(self.imageFileName) + '\n'
+ " Scale length [pixels]: %s" %(self.scaleLength) + '\n'
+ " Scale value [mm]: %.3f" %(self.scaleValue),
loc='left', fontsize=10)
if self.scale_object == None:
self.scale_object, = self.ax0.plot([point1Scale[0], point2Scale[0]],
[point1Scale[1], point2Scale[1]],
alpha=1.0, c='purple', lw=2)
else:
self.scale_object.set_data([point1Scale[0], point2Scale[0]],
[point1Scale[1], point2Scale[1]])
self.scaleValue_object.set_position((point1Scale[0], point1Scale[1]))
self.drawProfile(resetAxis=True)
#------------------------------------------------------------------
def update_lineWithWidth(self):
if self.lineWithWidth != None:
self.lineWithWidth.remove()
self.lineWithWidth = None
if self.profileLinewidth > 1:
xdata = list(self.line_object.get_xdata())
ydata = list(self.line_object.get_ydata())
line = LineString([(xdata[0], ydata[0]), (xdata[1], ydata[1])])
dilated = line.buffer(self.profileLinewidth/2., cap_style=2, join_style=1)
self.lineWithWidth, = self.ax0.plot(*dilated.exterior.xy, alpha=self.alpha_default, c='red', lw=2)
#------------------------------------------------------------------
def update_peaksExtractedPlot(self, resetAxis=True):
self.ax1.set_visible(True)
if not resetAxis:
xlim = self.ax1.get_xlim()
ylim = self.ax1.get_ylim()
self.ax1.clear()
self.ax1.grid(linestyle='dotted')
self.ax1.set_facecolor('whitesmoke')
self.ax1.yaxis.set_visible(False)
self.ax1.axvline(x=0, linestyle='dashed', color='gray', alpha=0.8)
if not resetAxis:
self.ax1.set_xlim(xlim)
self.ax1.set_ylim(ylim)
else:
self.ax1.set_ylim(-5,5)
lengthPeaks = []
for n, peaksExtracted in enumerate(self.peaksExtractedList):
posPeaks = peaksExtracted.get_offsets()
if len(lengthPeaks) == 0:
lengthPeaks.append(0)
else:
lengthPeaks.append(lengthPeaks[-1]) # segments are contiguous
self.ax1.axvline(x=lengthPeaks[-1], linestyle='dashed', color='gray', alpha=0.8)