forked from jgagneastro/coffeegrindsize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coffeegrindsize.py
3223 lines (2386 loc) · 116 KB
/
coffeegrindsize.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#Import the required packages
from tkinter import filedialog
from tkinter import *
from PIL import ImageTk, Image
import time
import numpy as np
import webbrowser
import pandas as pd
import os
import sys
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.ticker as mticker
from matplotlib import path
#Set thick axes
from matplotlib import rc
rc("axes", linewidth=2)
#Temporary for debugging purposes
import pdb
stop = pdb.set_trace
# === Default Parameters for analysis and plotting ===
#Whether or not to display advanced options
def_display_advanced_options = False
#Expert mode with all the options
def_expert_mode = False
#Threshold to select reference dark pixel
#def_reference_threshold = 0.1 #First version (too agressive)
def_reference_threshold = 0.4 #Second version (seems better on Lido and Forte images)
#Smoothing along path to reference pixel
nsmooth = 3 #Not accessible yet in the GUI
#Maximum cost for disjoint particles
#def_maxcost = 0.07 #First version (too agressive)
#def_maxcost = 0.2 #Second version (seems better on Lido and Forte images)
def_maxcost = 0.35 #Third version (seems much better on Lido and Forte images)
#Default value for image thresholding (%)
def_threshold = 58.8
#Default value for the pixel scale (pixels/millimeters)
def_pixel_scale = None
#Default value for the maximum diameter of a single cluster (pixels)
#Smaller values will speed up the code slightly
def_max_cluster_axis = 100
#Default value for the minimum surface of a cluster (pixels squared)
def_min_surface = 5
#Default value for the minimum roundness of a cluster (no units)
#Roundness is defined as the ratio of cluster to all pixels in the smallest circle that encompasses all pixels of a cluster
def_min_roundness = 0
#Default X axis range for the histogram (variable units)
def_min_x_axis = 0.01
def_max_x_axis = 10
#Default coffee cell size estimate in microns
coffee_cell_size = 20.
#Default name for the session (used for output filenames)
def_session_name = "PSD_"+time.strftime("%Y%m%d_%Hh%Mm%Ss")
original_image_display_name = "Original"
threshold_image_display_name = "Thresholded"
outlines_image_display_name = "Cluster Outlines"
histogram_image_display_name = "Histograms"
#Default sizes for histogram bins
default_log_binsize = 0.05
default_binsize = 0.1
#List of reference objects with their diameters in millimeters
reference_objects_dict = {"Custom":None, "Canadian Quarter":23.81, "Canadian Dollar":26.5, "Canadian Dime":18.03, "Canadian Two Dollars":28.0, "Canadian Five Cents":21.3, "US Quarter":24.26, "US Dollar":26.92, "US Dime":17.91, "US Penny":19.05, "2 Euros":25.75, "1 Euro":23.25, "50 Euro Cents":24.25, "20 Euro Cents":22.25}
#Default output directory
def_output_dir = os.path.expanduser("~")
#Python class for comparison data
class Comparison:
def __init__(self, **kwds):
#This variable will add some required dictionary values
self.__dict__.update(kwds)
#Python class for the user interface window
class coffeegrindsize_GUI:
#Actions to be taken on initialization of user interface window
def __init__(self, root):
# === Set some object variables that will not be garbage collected ===
#This variable contains the output directory
self.output_dir = def_output_dir
#Expert mode has many more options
self.expert_mode = def_expert_mode
#This variable will contain the object of the image currently displayed
self.image_id = None
#This variable will keep track of the number of detected clusters
self.nclusters = None
self.comparison = Comparison(nclusters=None)
#Keep track of the mouse click mode
self.mouse_click_mode = None
#These variables will contain various PIL images
self.img = None
self.img_source = None
self.img_threshold = None
self.img_clusters = None
self.img_histogram = None
#These variables contain the starting point of line for drawing
self.linex_start = None
self.liney_start = None
self.line_obj = None
#These variables contain the polygon for analysis region
self.polygon_alpha = None
self.polygon_beta = None
self.selreg_current_line = None
self.cursor_text = None
#These variables will contain thresholding information
self.mask_threshold = None
self.mask_threshold_edge = None
#These variables will contain cluster information
self.cluster_data = None
#This is the display scale for zooming in/out
self.scale = 1.0
self.original_scale = 1.0
#Apply a maximal scale of three zoom-ins
self.max_scale = 8.0
#This variable controls the zoom directionality (+1 in/-1 out)
self.zoom_dir = 0
#Remember the root object for the full user interface so that the methods of coffeegrindsize_GUI can refer to it
self.master = root
#The first row where options or buttons will be displayed
self.options_row = 1
self.simple_options_row = 1
#The width of text entries for adjustable options
self.width_entries = 6
#Horizontal spaces around the option labels
self.title_padx = 12
#Horizontal and vertical spaces around the toolbar buttons
self.toolbar_padx = 6
self.toolbar_pady = 0
#Size in pixels of the canvas where the pictures and figures will be displayed
self.canvas_width = 1000
self.canvas_height = int(self.master.winfo_screenheight()*0.9-165)
#Set the last image position memory to its default center
self.last_image_x = self.canvas_width/2
self.last_image_y = self.canvas_height/2
#This variable contains the controller for "erase clusters" mode
self.erase_clusters_mode = False
#This variable contains the size of the erase tool at zero zoom
self.erase_circle_radius = 20
#This will contain the circle drawn next to the cursor
self.erasemode_current_circle = None
#Advanced options
self.display_advanced_options = def_display_advanced_options
self.reference_threshold_var = None
self.maxcost_var = None
#Set the window title
self.master.title("Coffee Particle Size Distribution by Jonathan Gagne")
#Create a toolbar with buttons to launch various steps of analysis
toolbar_bg = "gray90"
toolbar = Frame(self.master, bg=toolbar_bg)
toolbar.pack(side=TOP, fill=X)
#Create a second toolbar
toolbar2 = Frame(self.master, bg=toolbar_bg)
toolbar2.pack(side=TOP, fill=X)
#Create a status bar at the bottom of the window
self.status_var = StringVar()
self.status_var.set("Idle...")
status = Label(self.master, textvariable=self.status_var, anchor=W, bg="grey", relief=SUNKEN)
status.pack(side=BOTTOM, fill=X)
# === Initialize the main frame that will contain option buttons and settings and the image ===
self.container_options = Frame(root, width=720)
self.container_options.pack(side="left", fill=Y)#, expand=True)
#self.container_options.grid_rowconfigure(0, weight=1)
#self.container_options.grid_columnconfigure(0, weight=1)
options_width = 500
self.frame_options = Frame(self.container_options, width=options_width)
self.frame_options.grid(row=0, column=0, sticky="nsew", columnspan=1, rowspan=25)
# === Create another version of that frame that excludes advanced options
self.simple_frame_options = Frame(self.container_options, width=options_width)
self.simple_frame_options.grid(row=0, column=0, sticky="nsew", columnspan=1, rowspan=25)
# === Build the adjustable keyword options ===
#This adds a vertical spacing in the options frame
#self.label_separator()
#All options related to image scale
self.label_title("Physical Scale of the Image:")
if def_pixel_scale is None:
def_pix_len = None
else:
def_pix_len = def_pixel_scale*float(reference_objects_dict["Custom"])
#Length of the reference object
#Comment on March 3, 2019: To add support for simplified output, use argument simple_data_entry=simple_data_entry
self.pixel_length_var, self.pixel_length_id, self.simple_pixel_length_id = self.label_entry(def_pix_len, "Reference Pixel Length:", "pix", entry_id=True, clear_on_click=True)
self.physical_length_var, self.physical_length_id, self.simple_physical_length_id = self.label_entry(reference_objects_dict["Custom"], "Reference Physical Size:", "mm", entry_id=True, event_on_entry="update_pixel_scale", clear_on_click=True)
self.pixel_length_id.config(state=DISABLED)
self.simple_pixel_length_id.config(state=DISABLED)
#Angle of selection
self.physical_angle_var = StringVar()
#Provide a menu of reference objects
self.reference_object = self.dropdown_entry("Reference Object:", list(reference_objects_dict.keys()), self.change_reference_object)
#Physical size of one pixel in the coffee grounds picture
#For now this needs to be input manually
self.pixel_scale_var = self.label_entry(def_pixel_scale, "Pixel Scale:", "pix/mm", clear_on_click=True, event_on_entry="update_statistics")
#self.label_separator()
#All options related to image thresholding
self.label_title("Threshold Step:", advanced=True)
#Value of fractional threshold in units of flux in the blue channel of the image
self.threshold_var = self.label_entry(def_threshold, "Threshold:", "%", advanced=True, clear_on_click=True)
#self.label_separator()
#All options related to particle detection
self.label_title("Particle Detection Step:", advanced=True)
#Maximum cluster diameter that should be considered a valid coffee particle
self.max_cluster_axis_var = self.label_entry(def_max_cluster_axis, "Maximum Cluster Diameter:", "pix", advanced=True, clear_on_click=True)
#Minumum cluster surface that should be considered a valid coffee particle
self.min_surface_var = self.label_entry(def_min_surface, "Minimum Cluster Surface:", "pix²", advanced=True, clear_on_click=True)
#Minimum cluster roundness that should be considered a valid coffee particle
#Roundess is defined between 0 and 1 where 1 is a perfect circle. It represents the fraction of thresholded pixels inside the smallest circle that encompasses the farthest thresholded pixels in one cluster
self.min_roundness_var = self.label_entry(def_min_roundness, "Minimum Roundness:", "", advanced=True, clear_on_click=True)
#Threshold to select pixels dark enough to serve as a reference in the cost function in the cluster breakup step
if self.display_advanced_options is True:
self.reference_threshold_var = self.label_entry(def_reference_threshold, "Ref. Threshold:", "", advanced=True)
else:
if self.reference_threshold_var is None:
self.reference_threshold_var = StringVar()
self.reference_threshold_var.set(str(def_reference_threshold))
#Maximum cost in the cluster breakup step
if self.display_advanced_options is True:
self.maxcost_var = self.label_entry(def_maxcost, "Max. Cost:", "", advanced=True)
else:
if self.maxcost_var is None:
self.maxcost_var = StringVar()
self.maxcost_var.set(str(def_maxcost))
#Whether the Particle Detection step should be quick and approximate
self.quick_var = IntVar()
self.quick_var.set(0)
quick_checkbox = Checkbutton(self.frame_options, text="Quick & Approximate", variable=self.quick_var)
quick_checkbox.grid(row=self.options_row, columnspan=2, sticky=E)
self.options_row += 1
self.label_separator(simpleonly=True)
#All options related to particle detection
self.label_title("Create Histogram Step:")
#self.default_histogram_choice = 10
#self.hist_choices = ["Number vs Diameter", "Number vs Surface", "Number vs Volume", "Mass vs Diameter", "Mass vs Surface", "Mass vs Volume", "Available mass vs Diameter", "Available mass vs Surface", "Available mass vs Volume", "Extracted mass vs Diameter", "Extracted mass vs Surface", "Extracted mass vs Volume", "Surface vs Diameter", "Surface vs Surface", "Surface vs Volume", "Extraction Yield Distribution"]
#self.hist_codes = ["num_diam", "num_surf", "num_vol", "mass_diam", "mass_surf", "mass_vol", "att_mass_diam", "att_mass_surf", "att_mass_vol", "ex_mass_diam", "ex_mass_surf", "ex_mass_vol", "surf_diam", "surf_surf", "surf_vol", "ey_dist"]
self.default_histogram_choice = 7
self.hist_choices = ["Number vs Diameter", "Number vs Surface", "Number vs Volume", "Mass vs Diameter", "Mass vs Surface", "Mass vs Volume", "Available mass vs Diameter", "Available mass vs Surface", "Available mass vs Volume", "Surface vs Diameter", "Surface vs Surface", "Surface vs Volume"]
self.hist_codes = ["num_diam", "num_surf", "num_vol", "mass_diam", "mass_surf", "mass_vol", "av_mass_diam", "av_mass_surf", "av_mass_vol", "surf_diam", "surf_surf", "surf_vol"]
self.histogram_type = self.dropdown_entry("Histogram Options:", self.hist_choices, self.change_histogram_type, default_choice_index=self.default_histogram_choice)
self.legend_choices = ["Best", "Upper Right", "Upper Left", "Lower Right", "Lower Left", "Center Right", "Center Left", "Lower Center", "Upper Center", "Right", "Center"]
self.legend_type = self.dropdown_entry("Label Position:", self.legend_choices, self.change_histogram_type)
#Label for the data
self.data_label_var = self.label_entry("Current Data", "Data Label:", "", columnspan=2, width=self.width_entries*3, event_on_enter="create_histogram")
#Label for the comparison data
self.comparison_data_label_var, self.comparison_data_label_id, self.simple_comparison_data_label_id = self.label_entry("Comparison Data", "Comparison Label:", "", entry_id=True, columnspan=2, width=self.width_entries*3, event_on_enter="create_histogram")
#Deactivate by default
self.comparison_data_label_id.config(state=DISABLED)
self.simple_comparison_data_label_id.config(state=DISABLED)
#Whether the X axis of the histogram should be set manually
#This is a checkbox
self.xaxis_auto_var = IntVar()
self.xaxis_auto_var.set(1)
xaxis_auto_checkbox = Checkbutton(self.frame_options, text="Automated X axis | ", variable=self.xaxis_auto_var, command=self.xaxis_auto_event)
xaxis_auto_checkbox.grid(row=self.options_row, columnspan=1, sticky=E, column=0)
#X axis range for the histogram figure
self.xmin_var, self.xmin_var_id = self.label_entry(def_min_x_axis, "Min. X Axis:", "", entry_id=True, addcol=1, event_on_enter="create_histogram", advanced=True, clear_on_click=True)
#Whether the X axis of the histogram should be in logarithm format
#This is a checkbox
self.xlog_var = IntVar()
self.xlog_var.set(1)
xlog_checkbox = Checkbutton(self.frame_options, text="Log X axis | ", variable=self.xlog_var, command=self.xlog_event)
xlog_checkbox.grid(row=self.options_row, columnspan=1, sticky=E, column=0)
self.xmax_var, self.xmax_var_id = self.label_entry(def_max_x_axis, "Max. X Axis:", "", entry_id=True, addcol=1, event_on_enter="create_histogram", advanced=True, clear_on_click=True)
#By default these options are disabled
self.xmin_var_id.config(state=DISABLED)
self.xmax_var_id.config(state=DISABLED)
self.options_row += 1
#Whether the number of bins should be automated
#This is a checkbox
self.nbins_auto_var = IntVar()
self.nbins_auto_var.set(1)
nbins_auto_checkbox = Checkbutton(self.frame_options, text="Automated bins | ", variable=self.nbins_auto_var, command=self.nbins_auto_event)
nbins_auto_checkbox.grid(row=self.options_row, columnspan=1, column=0, sticky=E)
#self.options_row += 1
#X axis range for the histogram figure
self.nbins_var, self.nbins_var_id = self.label_entry(10, "Num. bins:", "", entry_id=True, addcol=1, event_on_enter="create_histogram", advanced=True, clear_on_click=True)
#By default this option is disabled
self.nbins_var_id.config(state=DISABLED)
#self.label_separator()
#All options related to saving output data
self.label_title("Output Options:", advanced=True)
#Button to select an output directory
output_dir_button = Button(self.frame_options, text="Select Output Directory:", command=self.select_output_dir)
output_dir_button.grid(row=self.options_row, sticky=E)
#Display current output dir
self.output_dir_var, self.output_dir_label_id = self.label_entry(self.output_dir, "", "", entry_id=True, columnspan=2, width=self.width_entries*3, advanced=True)
self.output_dir_label_id.config(state=DISABLED)
self.options_row += 1
#The base of the output file names
self.session_name_var = self.label_entry(def_session_name, "Base of File Names:", "", columnspan=2, width=self.width_entries*3, advanced=True)
self.label_separator(simpleonly=True)
#All options related to image display
self.label_title("Display Options:")
#Select the display type
choices = [original_image_display_name, threshold_image_display_name, outlines_image_display_name, histogram_image_display_name]
self.display_type = self.dropdown_entry("Display Type:", choices, self.change_display_type)
#Remember the previous display type in case of error
self.previous_display_type = choices[0]
self.label_separator(simpleonly=True)
self.label_separator(simpleonly=True)
#Button to zoom in
#self.zoom_in_button = Button(self.frame_options, text="Zoom In", command=self.zoom_in_button)
#self.zoom_in_button.grid(row=self.options_row, column=0, columnspan=1, sticky=E)
#self.zoom_out_button = Button(self.frame_options, text="Zoom Out", command=self.zoom_out_button)
#self.zoom_out_button.grid(row=self.options_row, column=1, columnspan=1, sticky=W)
#Button for resetting zoom in the displayed image
self.reset_zoom_button = Button(self.frame_options, text="Reset View", command=self.reset_zoom)
self.reset_zoom_button.grid(row=self.options_row, column=2, columnspan=1, sticky=W)
self.options_row += 1
#Simplified versions of zoom buttons
self.simple_zoom_in_button = Button(self.simple_frame_options, text="Zoom In", command=self.zoom_in_button)
self.simple_zoom_in_button.grid(row=self.simple_options_row, column=0, columnspan=1, sticky=E)
self.simple_zoom_out_button = Button(self.simple_frame_options, text="Zoom Out", command=self.zoom_out_button)
self.simple_zoom_out_button.grid(row=self.simple_options_row, column=1, columnspan=1, sticky=W)
self.simple_reset_zoom_button = Button(self.simple_frame_options, text="Reset View", command=self.reset_zoom)
self.simple_reset_zoom_button.grid(row=self.simple_options_row, column=2, columnspan=1, sticky=W)
self.simple_options_row += 1
#Button for resetting all options to default
reset_params_button = Button(self.frame_options, text="Reset All Parameters", command=self.reset_status)
reset_params_button.grid(row=self.options_row, column=1, columnspan=2, sticky=E)
#Simplified version of button
simple_reset_params_button = Button(self.simple_frame_options, text="Reset All Parameters", command=self.reset_status)
simple_reset_params_button.grid(row=self.simple_options_row, column=1, columnspan=2, sticky=E)
#If expert mode is already set then display it
if self.expert_mode is True:
self.frame_options.tkraise()
# === Create a frame to display some stats ===
frame_stats_bg = "gray60"
self.frame_stats = Frame(self.container_options, bg=frame_stats_bg, padx=2, pady=10)
self.frame_stats.grid(row=0, column=1, sticky="new", rowspan=1)
title_label = Label(self.frame_stats, text="Properties of the Particle Distribution:", font='Helvetica 16 bold', bg=frame_stats_bg)
title_label.grid(row=0, sticky=W, padx=self.title_padx, columnspan=12)
stats_colsep_width = 3
stats_row = 1
stats_column = 0
stats_entry_width = 5
self.diam_average_var = StringVar()
self.diam_average_var.set("None")
diam_average_label = Label(self.frame_stats, text="Average Diameter:", bg=frame_stats_bg, font='Helvetica 14 bold')
diam_average_label.grid(row=stats_row, sticky=E, column=stats_column)
diam_average_entry = Label(self.frame_stats, textvariable=self.diam_average_var, width=stats_entry_width, bg=frame_stats_bg)
diam_average_entry.grid(row=stats_row, column=stats_column+1)
unit_label = Label(self.frame_stats, text="(mm)", bg=frame_stats_bg)
unit_label.grid(row=stats_row, column=stats_column+2, sticky=W)
stats_row += 1
self.diam_stddev_var = StringVar()
self.diam_stddev_var.set("None")
diam_stddev_label = Label(self.frame_stats, text="Scatter in Diameter:", bg=frame_stats_bg, font='Helvetica 14 bold')
diam_stddev_label.grid(row=stats_row, sticky=E, column=stats_column)
diam_stddev_entry = Label(self.frame_stats, textvariable=self.diam_stddev_var, width=stats_entry_width, bg=frame_stats_bg)
diam_stddev_entry.grid(row=stats_row, column=stats_column+1)
unit_label = Label(self.frame_stats, text="(mm)", bg=frame_stats_bg)
unit_label.grid(row=stats_row, column=stats_column+2, sticky=W)
stats_column += 3
stats_row =1
separator_label = Label(self.frame_stats, text="", width=stats_colsep_width, bg=frame_stats_bg)
separator_label.grid(row=stats_row, column=stats_column)
stats_column += 1
self.surf_average_var = StringVar()
self.surf_average_var.set("None")
surf_average_label = Label(self.frame_stats, text="Average Surface:", bg=frame_stats_bg, font='Helvetica 14 bold')
surf_average_label.grid(row=stats_row, sticky=E, column=stats_column)
surf_average_entry = Label(self.frame_stats, textvariable=self.surf_average_var, width=stats_entry_width, bg=frame_stats_bg)
surf_average_entry.grid(row=stats_row, column=stats_column+1)
unit_label = Label(self.frame_stats, text="(mm²)", bg=frame_stats_bg)
unit_label.grid(row=stats_row, column=stats_column+2, sticky=W)
stats_row += 1
self.surf_stddev_var = StringVar()
self.surf_stddev_var.set("None")
surf_stddev_label = Label(self.frame_stats, text="Scatter in Surface:", bg=frame_stats_bg, font='Helvetica 14 bold')
surf_stddev_label.grid(row=stats_row, sticky=E, column=stats_column)
surf_stddev_entry = Label(self.frame_stats, textvariable=self.surf_stddev_var, width=stats_entry_width, bg=frame_stats_bg)
surf_stddev_entry.grid(row=stats_row, column=stats_column+1)
unit_label = Label(self.frame_stats, text="(mm²)", bg=frame_stats_bg)
unit_label.grid(row=stats_row, column=stats_column+2, sticky=W)
# stats_column += 3
# stats_row =1
# separator_label = Label(self.frame_stats, text="", width=stats_colsep_width, bg=frame_stats_bg)
# separator_label.grid(row=stats_row, column=stats_column)
# stats_column += 1
# self.ey_average_var = StringVar()
# self.ey_average_var.set("None")
# ey_average_label = Label(self.frame_stats, text="Average EY:", bg=frame_stats_bg, font='Helvetica 14 bold')
# ey_average_label.grid(row=stats_row, sticky=E, column=stats_column)
# ey_average_entry = Label(self.frame_stats, textvariable=self.ey_average_var, width=stats_entry_width, bg=frame_stats_bg)
# ey_average_entry.grid(row=stats_row, column=stats_column+1)
# unit_label = Label(self.frame_stats, text="(%)", bg=frame_stats_bg)
# unit_label.grid(row=stats_row, column=stats_column+2, sticky=W)
# stats_row += 1
# self.ey_stddev_var = StringVar()
# self.ey_stddev_var.set("None")
# ey_stddev_label = Label(self.frame_stats, text="Scatter in EY:", bg=frame_stats_bg, font='Helvetica 14 bold')
# ey_stddev_label.grid(row=stats_row, sticky=E, column=stats_column)
# ey_stddev_entry = Label(self.frame_stats, textvariable=self.ey_stddev_var, width=stats_entry_width, bg=frame_stats_bg)
# ey_stddev_entry.grid(row=stats_row, column=stats_column+1)
# unit_label = Label(self.frame_stats, text="(%)", bg=frame_stats_bg)
# unit_label.grid(row=stats_row, column=stats_column+2, sticky=W)
stats_column += 3
stats_row = 1
separator_label = Label(self.frame_stats, text="", width=stats_colsep_width, bg=frame_stats_bg)
separator_label.grid(row=stats_row, column=stats_column)
stats_column += 1
self.eff_var = StringVar()
self.eff_var.set("None")
eff_label = Label(self.frame_stats, text="Efficiency:", bg=frame_stats_bg, font='Helvetica 14 bold')
eff_label.grid(row=stats_row, sticky=E, column=stats_column)
eff_entry = Label(self.frame_stats, textvariable=self.eff_var, width=stats_entry_width, bg=frame_stats_bg)
eff_entry.grid(row=stats_row, column=stats_column+1)
unit_label = Label(self.frame_stats, text="(%)", bg=frame_stats_bg)
unit_label.grid(row=stats_row, column=stats_column+2, sticky=W)
stats_row += 1
self.q_var = StringVar()
self.q_var.set("None")
eff_label = Label(self.frame_stats, text="Quality:", bg=frame_stats_bg, font='Helvetica 14 bold')
eff_label.grid(row=stats_row, sticky=E, column=stats_column)
eff_entry = Label(self.frame_stats, textvariable=self.q_var, width=stats_entry_width, bg=frame_stats_bg)
eff_entry.grid(row=stats_row, column=stats_column+1)
unit_label = Label(self.frame_stats, text="", bg=frame_stats_bg)
unit_label.grid(row=stats_row, column=stats_column+2, sticky=W)
# === Create a canvas to display images and figures ===
#Initialize the image canvas
image_canvas_bg = "gray40"
self.image_canvas = Canvas(self.container_options, width=self.canvas_width, height=self.canvas_height, bg=image_canvas_bg)
self.image_canvas.grid(row=1, column=1, sticky=N, rowspan=24)
#Prevent the image canvas to shrink when labels are placed in it
self.image_canvas.pack_propagate(0)
#Set focus on image canvas
self.image_canvas.focus_set()
#Display a label when no image was loaded
self.noimage_label = Label(self.image_canvas, text="No Image Loaded", anchor=CENTER, bg=image_canvas_bg, font='Helvetica 22 bold', width=self.canvas_width, height=self.canvas_height)
self.noimage_label.pack(side=LEFT)
# === Populate the toolbar with buttons for analysis ===
#Button to open an image of the coffee grounds picture
open_image_button = Button(toolbar, text="Open Image", command=lambda: self.open_image(None), highlightbackground=toolbar_bg)
open_image_button.pack(side=LEFT, padx=self.toolbar_padx, pady=self.toolbar_pady)
#Button to select a reference object
ref_obj_button = Button(toolbar, text="Select Reference Object", command=lambda: self.select_reference_object_mouse(None), highlightbackground=toolbar_bg)
ref_obj_button.pack(side=LEFT, padx=self.toolbar_padx, pady=self.toolbar_pady)
#Button to select region containing the coffee grounds
region_button = Button(toolbar, text="Select Analysis Region", command=lambda: self.select_region(None), highlightbackground=toolbar_bg)
region_button.pack(side=LEFT, padx=self.toolbar_padx, pady=self.toolbar_pady)
#Button to apply image threshold
threshold_image_button = Button(toolbar, text="Threshold Image", command=lambda: self.threshold_image(None), highlightbackground=toolbar_bg)
threshold_image_button.pack(side=LEFT, padx=self.toolbar_padx, pady=self.toolbar_pady)
#Button to launch the particle detection analysis
psd_button = Button(toolbar, text="Launch Particle Detection", command=lambda: self.launch_psd(None),highlightbackground=toolbar_bg)
psd_button.pack(side=LEFT, padx=self.toolbar_padx, pady=self.toolbar_pady)
#Button to erase some clusters
erase_button = Button(toolbar, text="Erase Clusters", command=lambda: self.erase_clusters(None), highlightbackground=toolbar_bg)
erase_button.pack(side=LEFT, padx=self.toolbar_padx, pady=self.toolbar_pady)
#Button to display histogram figures
histogram_button = Button(toolbar, text="Create Histogram", command=lambda: self.create_histogram(None), highlightbackground=toolbar_bg)
histogram_button.pack(side=LEFT, padx=self.toolbar_padx, pady=self.toolbar_pady)
#Read Blog Button
#Button to open blog
blog_button = Button(toolbar, text="Read Coffee Ad Astra Blog", command=self.blog_goto, highlightbackground=toolbar_bg)
blog_button.pack(side=RIGHT, padx=self.toolbar_padx, pady=self.toolbar_pady)
#Downsample button
downsample_button = Button(toolbar2, text="Reduce Image Quality", command=self.downsample_image, highlightbackground=toolbar_bg)
downsample_button.pack(side=LEFT, padx=self.toolbar_padx, pady=self.toolbar_pady)
#Button to load data from disk
load_data_button = Button(toolbar2, text="Load Data", command=lambda: self.load_data(None), highlightbackground=toolbar_bg)
load_data_button.pack(side=LEFT, padx=self.toolbar_padx, pady=self.toolbar_pady)
#Button to load comparison data from disk
load_comparison_data_button = Button(toolbar2, text="Load Comparison Data", command=lambda: self.load_comparison_data(None), highlightbackground=toolbar_bg)
load_comparison_data_button.pack(side=LEFT, padx=self.toolbar_padx, pady=self.toolbar_pady)
#Button to flush comparison data
flush_comparison_data_button = Button(toolbar2, text="Flush Comparison Data", command=self.flush_comparison_data, highlightbackground=toolbar_bg)
flush_comparison_data_button.pack(side=LEFT, padx=self.toolbar_padx, pady=self.toolbar_pady)
#Button to output data to the disk
save_button = Button(toolbar2, text="Save Data", command=lambda: self.save_data(None), highlightbackground=toolbar_bg)
save_button.pack(side=LEFT, padx=self.toolbar_padx, pady=self.toolbar_pady)
#Button to save histogram to disk
savehist_button = Button(toolbar2, text="Save View", command=lambda: self.save_histogram(None), highlightbackground=toolbar_bg)
savehist_button.pack(side=LEFT, padx=self.toolbar_padx, pady=self.toolbar_pady)
#Quit button
quit_button = Button(toolbar2, text="Quit", command=self.quit_gui, highlightbackground=toolbar_bg)
quit_button.pack(side=RIGHT, padx=self.toolbar_padx, pady=self.toolbar_pady)
#Reset button
reset_button = Button(toolbar2, text="Reboot", command=self.reset_gui, highlightbackground=toolbar_bg)
reset_button.pack(side=RIGHT, padx=self.toolbar_padx, pady=self.toolbar_pady)
#Help button
help_button = Button(toolbar2, text="Help", command=self.launch_help, highlightbackground=toolbar_bg)
help_button.pack(side=RIGHT, padx=self.toolbar_padx, pady=self.toolbar_pady)
# === Create a menu bar (File, Edit...) ===
menu = Menu(root)
root.config(menu=menu)
#Create a FILE submenu
subMenu = Menu(menu)
menu.add_cascade(label="File", menu=subMenu)
#Add an option to open images from disk
subMenu.add_command(label="Open Image...", command=lambda: self.open_image(None))
subMenu.add_separator()
#Add an option to downsample images
subMenu.add_command(label="Reduce Image Quality...", command=self.downsample_image)
#subMenu.add_command(label="Toggle Advanced Options...", command=self.toggle_advanced_options)
subMenu.add_separator()
#Expert mode with all options
subMenu.add_command(label="Turn Expert Mode On/Off...", command=self.toggle_expert_mode)
subMenu.add_separator()
#Add an option for debugging
subMenu.add_command(label="Python Debugger...", command=self.pdb_call)
subMenu.add_separator()
#Add an option to quit
subMenu.add_command(label="Quit", command=self.quit_gui)
# === Create drag and zoom options for the image canvas ===
#Always keep track of the mouse position (this is used for zooming toward the cursor)
self.image_canvas.bind('<Motion>', self.motion)
#Set up key bindings for dragging the image
self.image_canvas.bind("<ButtonPress-1>", self.move_start)
self.image_canvas.bind("<ButtonRelease-1>", self.release_mouse)
self.image_canvas.bind("<B1-Motion>", self.move_move)
#Set up key bindings for drawing a line
#self.image_canvas.bind("<ButtonPress-2>", self.line_start)
#self.image_canvas.bind("<B2-Motion>", self.line_move)
#Set up key bindings for zooming in and out with the i/o keys
self.image_canvas.bind_all("<Command-i>", self.zoom_in)
self.image_canvas.bind_all("<Command-o>", self.zoom_out
)
#Various shortcuts
self.master.bind_all("<Command-m>", self.open_image)
self.master.bind_all("<Command-r>", self.select_reference_object_mouse)
self.master.bind_all("<Command-a>", self.select_region)
self.master.bind_all("<Command-t>", self.threshold_image)
self.master.bind_all("<Command-p>", self.launch_psd)
self.master.bind_all("<Command-h>", self.create_histogram)
self.master.bind_all("<Command-s>", self.save_data)
self.master.bind_all("<Command-l>", self.load_data)
self.master.bind_all("<Control-c>", self.load_comparison_data)
self.master.bind_all("<Control-v>", self.save_histogram)
self.master.bind_all("<Command-e>", lambda event: self.toggle_expert_mode())
#Set up key binding for data analysis selection quit
self.image_canvas.bind_all("<Escape>", self.quit_region_select)
self.image_canvas.bind_all("<Return>", self.quit_region_select)
#Method to refresh histograms when xlog is toggled
def xlog_event(self):
#If there is already a histogram in play, refresh it
if self.img_histogram is not None:
self.create_histogram(None)
#Method to refresh histograms when automated bins are changed
def nbins_auto_event(self):
#If not automated then enable the option
if self.nbins_auto_var.get() == 0:
self.nbins_var_id.config(state=NORMAL)
#If automated then disable the option
if self.nbins_auto_var.get() == 1:
self.nbins_var_id.config(state=DISABLED)
#If there is already a histogram in play, refresh it
if self.img_histogram is not None:
self.create_histogram(None)
#Method to set the X axis options to automated
def xaxis_auto_event(self):
#If there is already a histogram in play, refresh it
if self.img_histogram is not None:
self.create_histogram(None)
#If not automated then enable the parameters
if self.xaxis_auto_var.get() == 0:
self.xmin_var_id.config(state=NORMAL)
self.xmax_var_id.config(state=NORMAL)
self.simple_xmin_var_id.config(state=NORMAL)
self.simple_xmax_var_id.config(state=NORMAL)
#If automated then disable the parameters
if self.xaxis_auto_var.get() == 1:
self.xmin_var_id.config(state=DISABLED)
self.xmax_var_id.config(state=DISABLED)
self.simple_xmin_var_id.config(state=DISABLED)
self.simple_xmax_var_id.config(state=DISABLED)
#Method to select the reference object in the image with the mouse
def select_reference_object_mouse(self, event):
#Verify that an image is loaded
if self.img_source is None:
#Update the user interface status
self.status_var.set("Original Image not Loaded Yet... Use Open Image Button...")
#Update the user interface
self.master.update()
#Return to caller
return
#Change the mouse click mode
self.mouse_click_mode = "SELECT_REFERENCE_OBJECT_READY"
#Update the user interface status
self.status_var.set("Use your mouse to click on one side of the reference object... You will then need to click again to set up a measuring line...")
#Update the user interface
self.master.update()
#Method to select analysis region
def select_region(self, event):
#Quit selection if already in select region mode
if self.mouse_click_mode == "SELECT_REGION":
self.quit_region_select(None)
return
#Verify that an image is loaded
if self.img_source is None:
#Update the user interface status
self.status_var.set("Original Image not Loaded Yet... Use Open Image Button...")
#Update the user interface
self.master.update()
#Return to caller
return
#Delete all currently drawn lines
self.image_canvas.delete(self.image_canvas.find_withtag("line"))
#Reset the region if it exists
self.polygon_alpha = None
self.polygon_beta = None
#Redraw the selected image
self.redraw(x=self.last_image_x, y=self.last_image_y)
#Update the user interface status
self.status_var.set("Click on the image to draw a polygon enclosing the coffee grounds, then press q...")
#Update the user interface
self.master.update()
#Change mouse click mode
self.mouse_click_mode = "SELECT_REGION"
#Method to finish analysis region selection
def quit_region_select(self, event):
#If the 'Erase Clusters' mode was selected then this is what needs to be quit
if self.erase_clusters_mode is True:
#Update the user interface status
self.status_var.set("The 'Erase Clusters' mode was deactivated.")
#Update the user interface
self.master.update()
#Update "Erase Clusters" internal status and return
self.erase_clusters_mode = False
return
#2019 March 3 this is not needed anymore because we now use escape or return
#Only active if image canvas has focus
#if self.master.focus_get() != self.image_canvas:
# return
#Only active in SELECT_REGION mode
if self.mouse_click_mode == "SELECT_REGION":
#Change mouse click mode
self.mouse_click_mode = None
#Destroy current mobile line if it exists
if self.selreg_current_line is not None:
self.image_canvas.delete(self.selreg_current_line)
self.selreg_current_line = None
#If there are too few polygon corners just quit
if self.polygon_alpha is None:
polysize = 0
else:
polysize = self.polygon_alpha.size
if polysize < 3:
#Delete all currently drawn lines
self.image_canvas.delete(self.image_canvas.find_withtag("line"))
#Reset the polygon region
self.polygon_alpha = None
self.polygon_beta = None
#Update the user interface status
self.status_var.set("Analysis Region Did Not Have Enough Corners (at least 3 are needed)...")
else:
#Add last polygon corner
self.polygon_alpha = np.append(self.polygon_alpha, self.polygon_alpha[0])
self.polygon_beta = np.append(self.polygon_beta, self.polygon_beta[0])
#Update the user interface status
self.status_var.set("Analysis Region Was Set...")
#Redraw image
self.redraw(x=self.last_image_x, y=self.last_image_y)
#Update the user interface
self.master.update()
#Method to open blog web page
def blog_goto(self, *args):
webbrowser.open("https://coffeeadastra.com")
#Method to change the reference object on the image
def change_reference_object(self, *args):
#Set the physical size of the reference object
self.physical_length_var.set(reference_objects_dict[self.reference_object.get()])
#Enable or disable the manual data entry depending on dictionary value
if self.reference_object.get() == "Custom":
self.physical_length_id.config(state=NORMAL)
self.simple_physical_length_id.config(state=NORMAL)
else:
self.physical_length_id.config(state=DISABLED)
self.simple_physical_length_id.config(state=DISABLED)
#Update the resulting pixel scale
self.update_pixel_scale()
#Update the GUI status
self.status_var.set("Reference Object set to "+self.reference_object.get()+"...")
#Update the user interface
self.master.update()
#Method to update the pixel scale
def update_pixel_scale(self):
#Calculate pixel scale. If an error arises then something was not a number
try:
pixel_scale = float(self.pixel_length_var.get())/float(self.physical_length_var.get())
#Make it a string
pixel_scale_str = "{0:.{1}f}".format(pixel_scale, 3)
except:
pixel_scale = None
pixel_scale_str = "None"
#Update the object value and display
self.pixel_scale_var.set(pixel_scale_str)
#Update the statistics
self.update_statistics()
#Method to register changes in the histogram type option
def change_histogram_type(self, *args):
#Deactivate log if EY distribution
if self.histogram_type.get() == "Extraction Yield Distribution":
self.xlog_var.set(0)
#If there is already a histogram in play, refresh it
if self.img_histogram is not None:
self.create_histogram(None)
def change_display_type(self, *args):
#Verify that original image is loaded
if self.display_type.get() == original_image_display_name:
if self.img_source is None:
#Update the user interface status
self.status_var.set("Original Image not Loaded Yet... Use Open Image Button...")
#Reset to previous display type
self.display_type.set(self.previous_display_type)
#Update the user interface
self.master.update()
#Return to caller
return
#Verify that thresholded image is loaded
if self.display_type.get() == threshold_image_display_name:
if self.img_threshold is None:
#Update the user interface status
self.status_var.set("Thresholded Image not Available Yet... Use Threshold Image Button...")
#Reset to previous display type
self.display_type.set(self.previous_display_type)
#Update the user interface
self.master.update()
#Return to caller
return
#Verify that cluster outlines image is loaded
if self.display_type.get() == outlines_image_display_name:
if self.img_clusters is None:
#Update the user interface status
self.status_var.set("Cluster Outlines Image not Available Yet... Use Launch Particle Detection Button...")
#Reset to previous display type
self.display_type.set(self.previous_display_type)
#Update the user interface
self.master.update()
#Return to caller
return
#Verify that cluster outlines image is loaded
if self.display_type.get() == histogram_image_display_name:
if self.img_histogram is None:
#Update the user interface status
self.status_var.set("Histogram Figure not Available Yet... Use Create Histogram Figure Button...")
#Reset to previous display type
self.display_type.set(self.previous_display_type)
#Update the user interface
self.master.update()
#Return to caller
return