Repository navigation
Expand file tree
/
Copy pathmicrostacking.py
More file actions
745 lines (637 loc) · 32 KB
/
Copy pathmicrostacking.py
File metadata and controls
745 lines (637 loc) · 32 KB
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
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# Copyright 2024 Julien Colafrancesco
#
import tkinter as tk
from tkinter import ttk
from ttkthemes import ThemedTk
from PIL import Image, ImageTk
import os
import serial
import gphoto2 as gp
import subprocess
import io
import time
import threading
import math
arduino = None # Variable to store the serial connection
camera_preview_active = False # Variable to track camera preview state
subprocess.call(["gio", "mount", "-s", "gphoto2"])
subprocess.call(["mkdir", "-p", "Capture"])
camera_connected = False # Variable to track camera connection state
try:
camera = gp.check_result(gp.gp_camera_new())
gp.check_result(gp.gp_camera_init(camera))
config = gp.check_result(gp.gp_camera_get_config(camera))
gp.gp_camera_capture_preview(camera)
camera_connected = True
except gp.GPhoto2Error as e:
print(f"Failed to initialize camera: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
def setup_window():
window = ThemedTk(theme="arc")
window.title("Microstacker")
window.geometry("1600x900") # Increased window size
return window
def setup_main_frame(window):
main_frame = ttk.Frame(window, padding="20", width=300)
main_frame.pack(side=tk.LEFT, fill=tk.Y)
return main_frame
def setup_camera_frame(main_frame):
camera_frame = ttk.LabelFrame(main_frame, text="Camera", padding="10")
camera_frame.pack(pady=10, fill=tk.BOTH, expand=True)
return camera_frame
def setup_image_frame(window):
image_frame = ttk.Frame(window, padding="10", style="Black.TFrame")
image_frame.pack(side=tk.RIGHT, padx=10, pady=10, expand=True, fill=tk.BOTH)
return image_frame
def setup_full_image_canvas(image_frame):
full_image_canvas = tk.Canvas(image_frame, background="black", bd=0, highlightthickness=0)
full_image_canvas.pack(expand=True, fill=tk.BOTH)
streaming_image = full_image_canvas.create_image(0, 0, anchor="center", image=None)
full_image_canvas.photo = None # Keep a reference to the PhotoImage object
return full_image_canvas, streaming_image
def setup_strip_frame(window):
strip_frame = ttk.Frame(window, padding="10")
strip_frame.pack(fill=tk.Y, expand=True, pady=(0, 10)) # Add padding to reduce height
return strip_frame
def setup_treeview(strip_frame):
style = ttk.Style()
style.configure("Treeview", rowheight=40) # Reduce row height to save space
treeview = ttk.Treeview(strip_frame, columns=("Image"), show="tree", selectmode='extended', style="Treeview") # Allow multiple selection
send_to_zerene_button = ttk.Button(strip_frame, text="Send to Zerene", command=lambda: send_to_zerene(treeview))
send_to_zerene_button.pack(side=tk.TOP, fill=tk.X, pady=5)
treeview.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar = ttk.Scrollbar(strip_frame, orient=tk.VERTICAL, command=treeview.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
treeview.configure(yscrollcommand=scrollbar.set)
treeview.image_dict = {}
treeview.image_thumbnails = {} # Dictionary to store image thumbnails
return treeview
def send_to_zerene(treeview):
selected_items = treeview.selection()
if selected_items:
folder_paths = []
for item in selected_items:
parent_item = treeview.parent(item)
if not parent_item:
folder_name = treeview.item(item, "text")
folder_paths.append(os.path.join('Capture', folder_name))
if folder_paths:
command_file_path = os.path.expanduser("~/.ZereneStacker/zerenstk.launchcmd")
if os.path.isfile(command_file_path):
with open(command_file_path, "r") as file:
command = file.read().strip()
command_with_folders = f"{command} -noSplashScreen {' '.join(folder_paths)}"
subprocess.Popen(command_with_folders, shell=True)
else:
print(f"Command file not found: {command_file_path}")
else:
print("Please select at least one folder in the tree view.")
else:
print("No item selected in the tree view.")
def setup_controls(main_frame):
connection_frame = setup_connection_frame(main_frame)
manual_controls_frame = setup_manual_controls_frame(main_frame)
stacking_frame = setup_stacking_frame(main_frame)
return connection_frame, manual_controls_frame, stacking_frame
def setup_connection_frame(main_frame):
connection_frame = ttk.LabelFrame(main_frame, text="Stepper Connection", padding="10")
connection_frame.pack(pady=10, fill=tk.BOTH, expand=True)
return connection_frame
def setup_manual_controls_frame(main_frame):
manual_controls_frame = ttk.LabelFrame(main_frame, text="Stepper Controls", padding="10")
manual_controls_frame.pack(pady=10, fill=tk.BOTH, expand=True)
return manual_controls_frame
def setup_stacking_frame(main_frame):
stacking_frame = ttk.LabelFrame(main_frame, text="Stacking", padding="10")
stacking_frame.pack(pady=10, fill=tk.BOTH, expand=True)
return stacking_frame
def setup_style():
style = ttk.Style()
style.configure("Black.TFrame", background="black")
style.configure("TLabel", background=style.lookup("TFrame", "background"))
style.configure("Green.TButton", foreground="green")
def create_label(frame, text, row, column, width=17, anchor=tk.E, pady=5, sticky=tk.W):
label = ttk.Label(frame, text=text, width=width, anchor=anchor)
label.grid(row=row, column=column, pady=pady, sticky=sticky)
return label
def create_combobox(frame, values, row, column, width=10, default_value=None, pady=5, sticky=tk.W):
combobox = ttk.Combobox(frame, values=values, width=width)
if default_value:
combobox.set(default_value)
combobox.grid(row=row, column=column, pady=pady, sticky=sticky)
return combobox
def create_spinbox(frame, from_, to, row, column, increment=1, width=10, default_value=None, pady=5, sticky=tk.W):
spinbox = ttk.Spinbox(frame, from_=from_, to=to, increment=increment, width=width)
if default_value:
spinbox.set(default_value)
spinbox.grid(row=row, column=column, pady=pady, sticky=sticky)
return spinbox
def linear_sRGB(c):
if c <= 0.04045:
return c / 12.92
else:
return pow((c + 0.055) / 1.055, 2.4)
def gamma_AdobeRGB(c):
if c <= 0.0:
return 0.0
return pow(c, 1/2.19921875)
def linear_AdobeRGB(c):
if c <= 0.0:
return 0.0
return pow(c, 2.19921875)
def gamma_sRGB(c):
if c <= 0.0031308:
return 12.92 * c
else:
return 1.055 * pow(c, 1/2.4) - 0.055
def lin_sRGB_to_XYZn(r, g, b):
Xn = r * 0.4124 + g * 0.3576 + b * 0.1805
Yn = r * 0.2126 + g * 0.7152 + b * 0.0722
Zn = r * 0.0193 + g * 0.1192 + b * 0.9505
return Xn, Yn, Zn
def XYZn_to_lin_sRGB(Xn, Yn, Zn):
r = Xn * 3.2406255 + Yn *-1.5372080 + Zn *-0.4986286
g = Xn *-0.9689307 + Yn * 1.8757561 + Zn * 0.0415175
b = Xn * 0.0557101 + Yn *-0.2040211 + Zn * 1.0569959
return r, g, b
def lin_AdobeRGB_to_XYZn(r, g, b):
Xn = r * 0.57667 + g * 0.18556 + b * 0.18823
Yn = r * 0.29734 + g * 0.62736 + b * 0.07529
Zn = r * 0.02703 + g * 0.07069 + b * 0.99134
return Xn, Yn, Zn
def XYZn_to_lin_AdobeRGB(Xn, Yn, Zn):
r = Xn * 2.04159 + Yn *-0.56501 + Zn *-0.34473
g = Xn *-0.96924 + Yn * 1.87597 + Zn * 0.04156
b = Xn * 0.01344 + Yn *-0.11836 + Zn * 1.01517
return r, g, b
def color_temperature_to_rgb(kelvin):
"""
A more accurate algorithm based on a different curve fit.
:param kelvin: Color temperature in degrees Kelvin
:return: Dictionary with red, green, and blue components
"""
temperature = kelvin / 100.0
red, green, blue = 0, 0, 0
if temperature < 66.0:
red = 255
else:
red = temperature - 55.0
red = 351.97690566805693 + 0.114206453784165 * red - 40.25366309332127 * math.log(red)
red = max(0, min(255, red))
if temperature < 66.0:
green = temperature - 2.0
green = -155.25485562709179 - 0.44596950469579133 * green + 104.49216199393888 * math.log(green)
green = max(0, min(255, green))
else:
green = temperature - 50.0
green = 325.4494125711974 + 0.07943456536662342 * green - 28.0852963507957 * math.log(green)
green = max(0, min(255, green))
if temperature >= 66.0:
blue = 255
else:
if temperature <= 20.0:
blue = 0
else:
blue = temperature - 10.0
blue = -254.76935184120902 + 0.8274096064007395 * blue + 115.67994401066147 * math.log(blue)
blue = max(0, min(255, blue))
red, green, blue = linear_sRGB(red / 255.0), linear_sRGB(green / 255.0), linear_sRGB(blue / 255.0)
x, y, z = lin_sRGB_to_XYZn(red, green, blue)
return XYZn_to_lin_AdobeRGB(x, y, z)
def rgb_to_color_temperature(r, g, b):
"""
Convert an RGB value to a color temperature.
:param rgb: Dictionary with red, green, and blue components
:return: Color temperature in Kelvin
"""
epsilon = 0.1
min_temperature = 1000
max_temperature = 40000
while max_temperature - min_temperature > epsilon:
temperature = (max_temperature + min_temperature) / 2.0
test_r, test_g, test_b = color_temperature_to_rgb(temperature)
if (test_b / test_r) >= (b / r):
max_temperature = temperature
else:
min_temperature = temperature
return round(temperature)
def main():
window = setup_window()
main_frame = setup_main_frame(window)
camera_frame = setup_camera_frame(main_frame)
image_frame = setup_image_frame(window)
strip_frame = setup_strip_frame(window)
treeview = setup_treeview(strip_frame)
full_image_canvas, streaming_image = setup_full_image_canvas(image_frame)
connection_frame, manual_controls_frame, stacking_frame = setup_controls(main_frame)
setup_style()
current_image_path = None
last_selected_image_path = None
resize_timer = None
stack_folder = None
stop_capture = False # Initialize stop_capture
def toggle_camera_preview():
global camera_preview_active
camera_preview_active = not camera_preview_active
if camera_preview_active:
camera_button.config(text="Stop Preview")
print("Camera preview activated")
update_camera_preview()
else:
camera_button.config(text="Start Preview")
print("Camera preview deactivated")
if last_selected_image_path:
show_full_image(last_selected_image_path)
update_cursor()
def capture_and_process_image():
file_path = capture_image()
process_captured_image(file_path, "Singles")
def capture_image():
try:
print("Capturing image")
start_time = time.time()
file_path = gp.check_result(gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE))
end_time = time.time()
print(f"Time taken to capture image: {end_time - start_time} seconds")
return file_path
except gp.GPhoto2Error as e:
print(f"Failed to capture image: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
def process_captured_image(file_path, folder):
try:
target_folder = os.path.join("Capture", folder)
os.makedirs(target_folder, exist_ok=True)
target = os.path.join(target_folder, file_path.name)
camera_file = gp.check_result(gp.gp_camera_file_get(camera, file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL))
gp.check_result(gp.gp_file_save(camera_file, target))
print(f"Image saved to {target}")
add_image_to_treeview(target)
show_full_image(target) # Display the last image captured
select_image_in_treeview(target) # Select the last image captured in the treeview
except gp.GPhoto2Error as e:
print(f"Failed to process captured image: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
def add_image_to_treeview(image_path):
image = Image.open(image_path)
image.thumbnail((50, 50), Image.NEAREST) # Adjust thumbnail size to fit within the tree view
photo = ImageTk.PhotoImage(image)
parent_folder = os.path.basename(os.path.dirname(image_path))
if parent_folder == "Capture":
parent_folder = os.path.basename(os.path.dirname(os.path.dirname(image_path)))
if parent_folder not in treeview.image_dict:
parent_id = treeview.insert('', 'end', text=parent_folder, open=True)
treeview.image_dict[parent_folder] = parent_id
else:
parent_id = treeview.image_dict[parent_folder]
image_name = os.path.basename(image_path)
new_item = treeview.insert(parent_id, 'end', text=image_name, image=photo)
treeview.image_thumbnails[new_item] = photo # Keep a reference to the PhotoImage object
treeview.selection_set(new_item)
treeview.see(new_item)
def select_image_in_treeview(image_path):
if os.path.isfile(image_path):
for item in treeview.get_children():
for sub_item in treeview.get_children(item):
if treeview.item(sub_item, "text") == os.path.basename(image_path):
treeview.selection_set(sub_item)
treeview.see(sub_item)
break
def show_full_image(image_path):
nonlocal current_image_path, last_selected_image_path
if not camera_preview_active and os.path.isfile(image_path):
current_image_path = image_path
last_selected_image_path = image_path
image = Image.open(image_path)
resize_and_display_image(image)
def resize_and_display_image(image):
global final_displayed_w, final_displayed_h
# Calculate the new size while maintaining the aspect ratio
frame_width = image_frame.winfo_width()
frame_height = image_frame.winfo_height()
if frame_width > 0 and frame_height > 0:
image_ratio = image.width / image.height
frame_ratio = frame_width / frame_height
if frame_ratio > image_ratio:
new_height = frame_height
new_width = int(new_height * image_ratio)
else:
new_width = frame_width
new_height = int(new_width / image_ratio)
if new_width > 0 and new_height > 0:
resized_image = image.resize((new_width, new_height), Image.NEAREST) # Use resize instead of thumbnail
final_displayed_w, final_displayed_h = new_width, new_height
photo = ImageTk.PhotoImage(resized_image)
full_image_canvas.itemconfig(streaming_image, image=photo)
full_image_canvas.coords(streaming_image, frame_width // 2, frame_height // 2) # Center the image
full_image_canvas.photo = photo # Keep a reference to the PhotoImage object
def schedule_final_resize():
nonlocal resize_timer
resize_timer = None
if not camera_preview_active and current_image_path:
image = Image.open(current_image_path)
resize_and_display_image(image)
def update_camera_preview():
if camera_preview_active:
try:
camera_file = gp.check_result(gp.gp_camera_capture_preview(camera))
file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
image = Image.open(io.BytesIO(file_data))
resize_and_display_image(image)
except gp.GPhoto2Error as e:
if e.code == gp.GP_ERROR_IO:
print(f"Failed to capture preview: {e}")
window.after(200, update_camera_preview) # Wait a bit before retrying
else:
print(f"Failed to capture preview: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
window.after(round(1000/30), update_camera_preview) # Increase interval to 200ms
else:
if last_selected_image_path:
show_full_image(last_selected_image_path)
def capture_stack_step(frame_index, num_frames, pre_shot_delay, angle):
if stop_capture or frame_index >= num_frames:
send_command_to_arduino("R")
launch_button.config(style="TButton")
return
def capture_next_image():
file_path = capture_image()
rotate_knob()
process_captured_image(file_path, stack_folder)
def rotate_knob():
send_command_to_arduino(f"U{angle}")
rot_time = 2 * angle / 360 # Time to rotate the stage by the specified angle
window.after(round(rot_time) * 1000, lambda: capture_stack_step(frame_index + 1, num_frames, pre_shot_delay, angle))
window.after(round(pre_shot_delay) * 1000, capture_next_image)
def capture_stack():
nonlocal stop_capture, stack_folder
stop_capture = False
num_frames = int(frames_spinbox.get())
pre_shot_delay = int(pre_shot_delay_spinbox.get())
angle = int(angle_stacking_spinbox.get())
stack_folder = f"Stack_{time.strftime('%Y%m%d_%H%M%S')}"
os.makedirs(stack_folder, exist_ok=True)
send_command_to_arduino("A")
launch_button.config(style="Green.TButton")
capture_stack_step(0, num_frames, pre_shot_delay, angle)
def stop_capture_stack():
nonlocal stop_capture
stop_capture = True
def on_treeview_select(event):
selected_item = treeview.selection()[0]
parent_item = treeview.parent(selected_item)
parent_folder = treeview.item(parent_item, "text")
image_name = treeview.item(selected_item, "text")
image_path = os.path.join("Capture", parent_folder, image_name)
show_full_image(image_path)
def load_images_from_folder(folder):
singles_id = None
folder_dict = {}
for root, _, files in os.walk(folder):
parent_folder = os.path.basename(root)
if parent_folder == "Capture":
parent_folder = os.path.basename(os.path.dirname(root))
if parent_folder not in folder_dict:
folder_dict[parent_folder] = []
for file in files:
if os.path.isfile(os.path.join(root, file)) and file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.cr2')):
image_path = os.path.join(root, file)
folder_dict[parent_folder].append(image_path)
for parent_folder in sorted(folder_dict.keys()):
if parent_folder: # Ensure parent_folder is not empty
parent_id = treeview.insert('', 'end', text=parent_folder, open=(parent_folder == "Singles"))
treeview.image_dict[parent_folder] = parent_id
if parent_folder == "Singles":
singles_id = parent_id
for image_path in sorted(folder_dict[parent_folder]):
image_name = os.path.basename(image_path)
new_item = treeview.insert(parent_id, 'end', text=image_name)
treeview.image_thumbnails[new_item] = image_path # Store the image path temporarily
return singles_id
def load_thumbnails():
for item in treeview.image_thumbnails:
image_path = treeview.image_thumbnails[item]
image = Image.open(image_path)
image.thumbnail((50, 50)) # Adjust thumbnail size to fit within the tree view
photo = ImageTk.PhotoImage(image)
treeview.item(item, image=photo)
treeview.image_thumbnails[item] = photo # Replace the path with the PhotoImage object
def load_images_thread():
load_thumbnails()
def display_first_image():
if singles_id and treeview.get_children(singles_id):
first_image_path = treeview.item(treeview.get_children(singles_id)[0], "text")
show_full_image(first_image_path)
treeview.selection_set(treeview.get_children(singles_id)[0])
treeview.see(treeview.get_children(singles_id)[0])
elif treeview.get_children():
first_image_path = treeview.item(treeview.get_children()[0], "text")
show_full_image(first_image_path)
select_image_in_treeview(first_image_path)
def on_resize(event):
strip_frame.config(width=int(250))
nonlocal resize_timer
if resize_timer is None:
resize_timer = window.after(round(100), schedule_final_resize)
def send_command_to_arduino(command):
global arduino
if arduino:
arduino.write(command.encode())
else:
print("Arduino not connected")
def move_up():
send_command_to_arduino("A")
send_command_to_arduino(f"U{angle_spinbox.get()}")
send_command_to_arduino("R")
def move_down():
send_command_to_arduino("A")
send_command_to_arduino(f"D{angle_spinbox.get()}")
send_command_to_arduino("R")
def update_ttys():
ttys = [f"/dev/{tty}" for tty in os.listdir('/dev') if tty.startswith('tty')]
tty_combobox['values'] = ttys
if ttys:
tty_combobox.set(ttys[-1]) # Set to the last tty in the list
def connect():
global arduino
if arduino and arduino.is_open:
arduino.close()
arduino = None
status_label.config(text="Status: Unconnected", foreground="red")
connect_button.config(text="Connect")
up_button.config(state=tk.DISABLED)
down_button.config(state=tk.DISABLED)
else:
tty = tty_combobox.get()
baudrate = baudrate_combobox.get()
try:
arduino = serial.Serial(tty, baudrate)
status_label.config(text="Status: Connected", foreground="green")
connect_button.config(text="Disconnect")
up_button.config(state=tk.NORMAL)
down_button.config(state=tk.NORMAL)
except Exception as e:
print(f"Failed to connect: {e}")
status_label.config(text="Status: Unconnected", foreground="red")
def populate_combobox(widget_name, combobox):
try:
OK, widget = gp.gp_widget_get_child_by_name(config, widget_name)
if OK >= gp.GP_OK:
values = [gp.gp_widget_get_choice(widget, i)[1] for i in range(gp.gp_widget_count_choices(widget))]
combobox['values'] = values
current_value = gp.gp_widget_get_value(widget)[1]
combobox.set(current_value)
except gp.GPhoto2Error as e:
print(f"Failed to get {widget_name} values: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
def set_camera_value(event, widget_name, combobox):
try:
OK, widget = gp.gp_widget_get_child_by_name(config, widget_name)
if OK >= gp.GP_OK:
widget.set_value(combobox.get())
camera.set_config(config)
except gp.GPhoto2Error as e:
print(f"Failed to set {widget_name} value: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
def on_whitebalance_change(event):
set_camera_value(event, 'whitebalance', white_balance_combobox)
update_cursor()
def update_cursor():
if white_balance_combobox.get() == "Color Temperature" and camera_preview_active:
full_image_canvas.config(cursor="crosshair")
else:
full_image_canvas.config(cursor="arrow")
def on_image_click(event):
if white_balance_combobox.get() == "Color Temperature" and camera_preview_active:
if camera_preview_active:
try:
camera_file = gp.check_result(gp.gp_camera_capture_preview(camera))
file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
img = Image.open(io.BytesIO(file_data))
except Exception as e:
print(f"Failed to retrieve camera preview image: {e}")
return
else:
img = Image.open(last_selected_image_path)
frame_w = image_frame.winfo_width()
frame_h = image_frame.winfo_height()
ix = event.x - (frame_w - final_displayed_w) // 2
iy = event.y - (frame_h - final_displayed_h) // 2
if 0 <= ix < final_displayed_w and 0 <= iy < final_displayed_h:
ratio_x = img.width / final_displayed_w
ratio_y = img.height / final_displayed_h
real_x = int(ix * ratio_x)
real_y = int(iy * ratio_y)
r, g, b = img.getpixel((real_x, real_y))[:3]
r, g, b = linear_AdobeRGB(r), linear_AdobeRGB(g), linear_AdobeRGB(b)
print(f"Pixel color at ({real_x}, {real_y}): R={r}, G={g}, B={b}")
try:
OK, ctemp_widget = gp.gp_widget_get_child_by_name(config, "colortemperature")
if OK >= gp.GP_OK:
current_temp = int(gp.gp_widget_get_value(ctemp_widget)[1])
cr, cg, cb = color_temperature_to_rgb(current_temp)
tr, tg, tb = color_temperature_to_rgb(6500)
r = r * cr / tr
g = g * cg / tg
b = b * cb / tb
new_temp = rgb_to_color_temperature(r, g, b)
choices = [gp.gp_widget_get_choice(ctemp_widget, i)[1] for i in range(gp.gp_widget_count_choices(ctemp_widget))]
numeric_choices = [int(choice) for choice in choices if choice.isdigit()]
closest_temp = min(numeric_choices, key=lambda x: abs(x - new_temp))
ctemp_widget.set_value(str(closest_temp))
camera.set_config(config)
print(f"Camera color temperature set to {closest_temp}")
except Exception as e:
print(f"Could not update camera color temperature: {e}")
# Add Shutter Speed control
shutter_speed_label = create_label(camera_frame, "Shutter Speed: ", row=2, column=0)
shutter_speed_combobox = create_combobox(camera_frame, values=[], row=2, column=1)
# Add ISO control
iso_label = create_label(camera_frame, "ISO: ", row=3, column=0)
iso_combobox = create_combobox(camera_frame, values=[], row=3, column=1)
# Add White Balance control
white_balance_label = create_label(camera_frame, "White Balance: ", row=4, column=0)
white_balance_combobox = create_combobox(camera_frame, values=[], row=4, column=1)
# Add Image Format control
image_format_label = create_label(camera_frame, "Image Format: ", row=5, column=0)
image_format_combobox = create_combobox(camera_frame, values=[], row=5, column=1)
iso_combobox.bind("<<ComboboxSelected>>", lambda event: set_camera_value(event, 'iso', iso_combobox))
shutter_speed_combobox.bind("<<ComboboxSelected>>", lambda event: set_camera_value(event, 'shutterspeed', shutter_speed_combobox))
white_balance_combobox.bind("<<ComboboxSelected>>", on_whitebalance_change)
image_format_combobox.bind("<<ComboboxSelected>>", lambda event: set_camera_value(event, 'imageformat', image_format_combobox))
full_image_canvas.bind("<Button-1>", on_image_click)
populate_combobox('iso', iso_combobox)
populate_combobox('shutterspeed', shutter_speed_combobox)
populate_combobox('whitebalance', white_balance_combobox)
populate_combobox('imageformat', image_format_combobox)
capture_button = ttk.Button(camera_frame, text="Capture", command=capture_and_process_image, width=15)
capture_button.grid(row=0, column=0, columnspan=2, pady=5, sticky=tk.W+tk.E)
camera_button = ttk.Button(camera_frame, text="Start Preview", command=toggle_camera_preview, width=15)
camera_button.grid(row=1, column=0, columnspan=2, pady=5, sticky=tk.W+tk.E)
update_button = ttk.Button(connection_frame, text="Update TTY", command=update_ttys)
update_button.grid(row=0, column=0, columnspan=2, pady=5, sticky=tk.W+tk.E)
tty_label = create_label(connection_frame, "Select TTY: ", row=1, column=0)
tty_combobox = create_combobox(connection_frame, values=[], row=1, column=1)
baudrate_label = create_label(connection_frame, "Baudrate: ", row=2, column=0)
baudrate_combobox = create_combobox(connection_frame, ["9600", "19200", "38400", "57600", "115200"], row=2, column=1, default_value="9600")
connect_button = ttk.Button(connection_frame, text="Connect", command=connect)
connect_button.grid(row=3, column=0, columnspan=2, pady=5, sticky=tk.W+tk.E)
status_label = ttk.Label(connection_frame, text="Status: Unconnected", foreground="red", anchor=tk.E)
status_label.grid(row=4, column=0, columnspan=2, pady=5)
update_ttys() # Update the list of TTYs at app initialization
window.after(1000, connect) # Try to connect to the selected TTY after updating the list
angle_label = create_label(manual_controls_frame, "Angle (degrees): ", row=0, column=0)
angle_spinbox = create_spinbox(manual_controls_frame, from_=0, to=360, row=0, column=1, default_value=15)
up_button = ttk.Button(manual_controls_frame, text="↑", command=move_up)
up_button.grid(row=1, column=0, columnspan=2, pady=5, sticky=tk.W+tk.E)
up_button.config(state=tk.DISABLED)
down_button = ttk.Button(manual_controls_frame, text="↓", command=move_down)
down_button.grid(row=2, column=0, columnspan=2, pady=5, sticky=tk.W+tk.E)
down_button.config(state=tk.DISABLED)
frames_label = create_label(stacking_frame, "Number of Frames: ", row=0, column=0)
frames_spinbox = create_spinbox(stacking_frame, from_=1, to=100, row=0, column=1, default_value=3)
pre_shot_delay_label = create_label(stacking_frame, "Pre-Shot Delay: ", row=1, column=0)
pre_shot_delay_spinbox = create_spinbox(stacking_frame, from_=0, to=60, row=1, column=1, default_value=1)
angle_stacking_label = create_label(stacking_frame, "Angle (degrees): ", row=3, column=0)
angle_stacking_spinbox = create_spinbox(stacking_frame, from_=0, to=360, row=3, column=1, default_value=30)
launch_button = ttk.Button(stacking_frame, text="Capture Stack", command=capture_stack, width=15)
launch_button.grid(row=4, column=0, columnspan=2, pady=5, sticky=tk.W+tk.E)
stop_button = ttk.Button(stacking_frame, text="Stop", command=stop_capture_stack, width=15)
stop_button.grid(row=5, column=0, columnspan=2, pady=5, sticky=tk.W+tk.E)
treeview.bind("<<TreeviewSelect>>", on_treeview_select)
singles_id = load_images_from_folder("Capture") # Load image names in the main thread
display_first_image()
threading.Thread(target=load_images_thread).start() # Load thumbnails in a separate thread
window.bind("<Configure>", on_resize) # Bind the resize event to update the image size
if not camera_connected:
camera_button.config(state=tk.DISABLED)
capture_button.config(state=tk.DISABLED)
shutter_speed_combobox.config(state=tk.DISABLED)
iso_combobox.config(state=tk.DISABLED)
white_balance_combobox.config(state=tk.DISABLED)
image_format_combobox.config(state=tk.DISABLED)
launch_button.config(state=tk.DISABLED)
stop_button.config(state=tk.DISABLED)
print("Camera controls disabled due to no camera connection")
window.mainloop()
if __name__ == "__main__":
main()