-
Notifications
You must be signed in to change notification settings - Fork 0
/
MicroScope_Cam_class102.py
351 lines (315 loc) · 16.4 KB
/
MicroScope_Cam_class102.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
#MicroScope CMOS Camera Viewer with Scale-Bar ... class102 is version for CMOS camera 2592x1944 @ 25fps
import os
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
import cv2
from PIL import Image, ImageTk, ImageOps #
class Application(tk.Frame):
def __init__(self, master):
super(Application, self).__init__(master)
self.pack()
self.master.geometry("1350x690+0+0") # TK window size(width x height & Left Top)
str_prog_name = os.path.basename(__file__) # get present program name
self.master.title( str_prog_name )
#Initialize view, camera CMOS spec:2592x1944 @ 25fps 1/1.8" Color IMX CMOS Image Sensor 3840x2160 @ 25fps;2592x1944 @ 25fps Pixel size=2×2μm
self.view_width = 864
self.view_height = 648
self.view_magnify = 1/4 # Camera to Picture ratio 3:1 .... change 1/3->1/4 for speed_up
self.camera_id = 0 # 0=PC_Cam 1=External_USB_Cam
self.frame_rate = 5 #25fps camera
self.disp_id = None #for picture animation
# Canvas
self.canvas = tk.Canvas(root, width=self.view_width, height=self.view_height, bg='gray')
self.canvas.pack(side=tk.LEFT,expand=True,anchor=tk.NW)
# on Canvas, bind mouse event(Left Click)
self.canvas.bind('<Button-1>', self.canvas_click)
self.canvas.pack(expand = True, fill = tk.BOTH)
#Default save file
file_name1 = "Capture.jpg"
self.typelist1 = [("Capture.jpg", ".jpg"),]
#self.ini_dir = os.path.dirname(__file__) # get present program directory
self.ini_dir =r'C:\Users\taniyama\Desktop'
self.file_path = os.path.join(self.ini_dir, file_name1)
#print (self.file_path)
self.count = 0
# Initialize show scale profile
self.show_scale = True # True= Show Scale , False= Hide Scale
self.relaylens_magnify = 0.53 # Zoom lens x0.35 -> x0.70 maxsize 0.7-> 0.53 #size is ?????
self.str_lens_magnify = 'x10' # Objective Lens x10 Default
self.lens_magnify = 10.0 # Objective Lens x10 Default
self.str_length = '100um' # Scale length
self.length = 100.0 # Scale length
self.pixel_length = 2.0 # 2.0um/Pixel
self.x0 = 350
self.y0 = 100
# Preset Color for Button(tkinter)
self.color_green = str('#ccffaa') #green
self.color_gray = str('#f2f2f2') #gray(Back ground color)
self.color_red = str('#ffaacc') #red
# Preset Color for Scale(opencv)
self.white = (255,255,255) #Color order is BGR on cv2(opencv)
self.red = (0,0,255) #BGR #RGB(255,0,0)
self.aqua = (255,255,0) #BGR #RGB(0,255,255)
self.green = (0,255,0)
self.black = (0,0,0)
self.color = self.white
self.str_color = 'white'
# frame1
frame1 = tk.Frame(root, bd=2, pady=5, padx=5)
frame1.pack(side=tk.RIGHT,expand=True,anchor=tk.NE)
#camera operation
self.btn_live = tk.Button(frame1, text='Play//Pause', command=self.btn_click, width=10, height=2, background=self.color_green)
self.btn_live.grid(row=0, column=0, padx=5, pady=5)
btn_exit = tk.Button(frame1, text='Exit', command=root.quit, width=10, height=2)
btn_exit.grid(row=0, column=1, padx=5, pady=5)
column_0 = ('0', '1', '2') #0:WebCam 1:Microscope USB Cam
btn_camera = tk.Button(frame1, text='Change Camera', command=self.Set_Camera(), width=15, height=2) # run in advance
btn_camera.grid(row=1, column=0, padx=5, pady=5)
self.combobox_0 = ttk.Combobox(frame1, height=1, width=10, justify='center', values=column_0)
self.combobox_0.insert(0, '0') #1:Microscope USB Cam
self.combobox_0.grid(row=1, column=1, padx=5, pady=5)
#Save picture
label_save_filename = tk.Label(frame1, text='Show save file path.')
label_save_filename.grid(row=2, column=0, padx=5, pady=5)
self.save_filename = tk.Text(frame1, height=4,width=25)
self.save_filename.grid(row=3, column=0, padx=5, pady=5)
self.save_filename.insert(tk.END, str(self.file_path))
btn_Set_Plot1 = tk.Button(frame1, text='Set file path', command=self.Set_File_Path, width=15, height=1)
btn_Set_Plot1.grid(row=4, column=0, padx=5, pady=5)
self.btn_save = tk.Button(frame1, text='Save Image File', command=self.Caputure_Image, width=15, height=2)
self.btn_save.grid(row=5, column=0, padx=5, pady=5)
#Show scale
btn_scale = tk.Button(frame1, text='Scale on/off', command=self.Show_Scale, width=15, height=1)
btn_scale.grid(row=6, column=0, padx=5, pady=5)
#Set Objective Lens
lbl_1 = tk.Label(frame1, text='Set Objective Lens')
lbl_1.grid(row=7, column=0, padx=5, pady=5)
column_1 = ('x5', 'x10', 'x20', 'x50', 'x100')
self.combobox_1 = ttk.Combobox(frame1, height=1, width=10, justify='center', values=column_1)
self.combobox_1.insert(0, self.str_lens_magnify)
self.combobox_1.bind('<<ComboboxSelected>>', self.Set_Objective_Lens)
self.combobox_1.grid(row=7, column=1, padx=5, pady=5)
#Set Scale-Bar Length
lbl_2 = tk.Label(frame1, text='Set Length')
lbl_2.grid(row=8, column=0, padx=5, pady=5)
column_2 = ('10um', '20um', '50um', '100um', '200um','500um','1000um')
self.combobox_2 = ttk.Combobox(frame1, height=1, width=10, justify='center', values=column_2)
self.combobox_2.insert(0, self.str_length)
self.combobox_2.bind('<<ComboboxSelected>>', self.Set_Length)
self.combobox_2.grid(row=8, column=1, padx=5, pady=5)
#Set Scale-Bar Color
column_3 = ('white', 'green', 'aqua', 'black', 'red')
lbl_2 = tk.Label(frame1, text='Set Color')
lbl_2.grid(row=9, column=0, padx=5, pady=5)
self.combobox_3 = ttk.Combobox(frame1, height=1, width=10, justify='center', values=column_3)
self.combobox_3.insert(0, self.str_color)
self.combobox_3.bind('<<ComboboxSelected>>', self.Set_Color)
self.combobox_3.grid(row=9, column=1, padx=5, pady=5)
#Load Camera driver configration
btn_Config = tk.Button(frame1, text='Set Camera Configuration', command=self.Set_Config, width=20,height=2, background=self.color_green)
btn_Config.grid(row=10, column=0, padx=5, pady=5)
#mouse click event
label_start_x = tk.Label(frame1, text='mouse_pos_x')
label_start_x.grid(row=11, column=0)
label_start_y = tk.Label(frame1, text='mouse_pos_y')
label_start_y.grid(row=12, column=0)
self.en_x0 = tk.Entry(frame1, width=10, justify='right')
self.en_x0.grid(row=11, column=1)
self.en_x0.insert(tk.END, self.x0)
self.en_y0 = tk.Entry(frame1, width=10, justify='right')
self.en_y0.grid(row=12, column=1)
self.en_y0.insert(0, self.y0)
#Notes
label_save_filename = tk.Label(frame1, text='Image View is shown in 1/4 scale.')
label_save_filename.grid(row=13, column=0, padx=5, pady=5)
label_save_filename = tk.Label(frame1, text='Move the Scale to where mouse is clicked.')
label_save_filename.grid(row=14, column=0, padx=5, pady=5)
def canvas_click(self, event):
'''Canvas mouse click event'''
self.x0 = int(event.x / self.view_magnify)
self.y0 = int(event.y / self.view_magnify)
self.en_x0.delete(0,'end')
self.en_y0.delete(0,'end')
self.en_x0.insert(tk.END, self.x0)
self.en_y0.insert(tk.END, self.y0)
return
def btn_click(self):
'''Play//Pause button '''
if self.disp_id is None:
# 動画を表示
self.disp_image()
self.btn_live.configure(bg = self.color_red) # live button color changed
self.btn_save.configure(bg = self.color_gray) # save button color changed
else:
# 動画を停止
self.after_cancel(self.disp_id)
self.disp_id = None
self.btn_live.configure(bg = self.color_gray) # live button color changed
self.btn_save.configure(bg = self.color_green) # save button color changed
return
def disp_image(self):
'''Show image on Canvas'''
# make image
self.make_image()
# canvas size
#canvas_width = self.canvas.winfo_width()
#canvas_height = self.canvas.winfo_height()
canvas_width = self.view_x
canvas_height = self.view_y
# Resize image to Canvas with original aspect ratio.
pil_image = ImageOps.pad(self.pil_image, (canvas_width, canvas_height))
# change PIL.Image to PhotoImage
self.photo_image = ImageTk.PhotoImage(image=pil_image)
# canva image
self.canvas.create_image(
canvas_width / 2, # location X&Y(Center of Canvas)
canvas_height / 2,
image=self.photo_image # image data
)
# show disp_image after 10msec
self.disp_id = self.after(10, self.disp_image)
return
def make_image(self):
# OpenCV to Canvas
ret, frame = self.capture.read()
if self.show_scale:
#size
line_thickness = 6
line_height= 20
font_size = 2.0
text_length = 300
#Write Scale text
cv2.putText(img=frame, text=self.str_length, org=(self.x0 - text_length, self.y0), fontFace=cv2.FONT_HERSHEY_SIMPLEX,
fontScale=font_size, color=self.color, thickness=line_thickness, lineType=cv2.LINE_AA)
#Draw Scale image length
self.multi_factor = self.lens_magnify * self.relaylens_magnify
pixels = self.length / self.pixel_length * self.multi_factor
length= int(pixels)
x_loc = self.x0
y_loc = self.y0
cv2.line(frame, (x_loc, y_loc), (x_loc+length, y_loc), self.color,thickness=line_thickness)
cv2.line(frame, (x_loc, y_loc), (x_loc, y_loc-line_height), self.color,thickness=line_thickness)
cv2.line(frame, (x_loc+length, y_loc), (x_loc+length, y_loc-line_height), self.color,thickness=line_thickness)
else:
pass
# BGR→RGB
#cv_image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
if frame.ndim == 2: # mono
cv_image = frame
if frame.shape[2] == 1: # mono (8bit)
cv_image = frame
elif frame.shape[2] == 3: # Color(24bit)
cv_image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
elif frame.shape[2] == 4: # Color with Transparent(32bit)
cv_image = cv2.cvtColor(frame, cv2.COLOR_BGRA2RGBA)
pil_image = Image.fromarray(cv_image)
self.pil_image = pil_image
return
def Set_File_Path(self):
#20221108 add defaultextension = "" ....automatically add extension
filename=filedialog.asksaveasfilename(initialdir=self.ini_dir, filetypes=self.typelist1, title="Set File_path", defaultextension = "")
if filename == "":
return
else:
self.file_path = filename
self.f_root, self.ext = os.path.splitext(self.file_path)
self.ini_dir = self.f_root
self.save_filename.delete('1.0','end') # Delete all
self.save_filename.insert(tk.END, str(self.file_path))
print('Set File_path =' , os.path.abspath(self.file_path))
return
def Caputure_Image(self):
'''Save picture'''
self.pil_image.save(self.file_path)
#self.create_modeless_dialog() # 2022/12/21 delete
tk.messagebox.showinfo(title="Image file saved", message="Image file saved.")
#self.pil_image.save('{}_{}.{}'.format(self.base_path, self.count, self.ext))
#self.count += 1
return
def Set_Camera(self):
try: # button color changed
self.btn_live.configure(bg = self.color_green) # live button color changed
self.btn_save.configure(bg = self.color_gray) # save button color changed
self.camera_id = int(self.combobox_0.get()) # camera_id
except:
pass
# Pause Camera and Change Camera
if self.disp_id is None:
pass
else:
# Pause camera
self.after_cancel(self.disp_id)
self.disp_id = None# Pause
try:
# release Camera
self.capture.release()
except:
pass
# Open Camera
self.capture = cv2.VideoCapture(self.camera_id)
#self.frame_prf_0=self.capture.get(cv2.CAP_PROP_FRAME_WIDTH) # get camera profile
#self.frame_prf_1=self.capture.get(cv2.CAP_PROP_FRAME_HEIGHT)
self.frame_prf_0 = 2592 #force write
self.frame_prf_1 = 1944
str_text = 'Camera_'+str(self.camera_id)+'\n'+'Width :'+str(self.frame_prf_0)+'\n'+'Height :' + str(self.frame_prf_1)
tk.messagebox.showinfo(title="Camera connected", message=str_text)
#camera Re-open with "cv2.CAP_DSHOW"
self.capture = cv2.VideoCapture(self.camera_id,cv2.CAP_DSHOW)
try:
self.capture.set(cv2.CAP_PROP_FRAME_WIDTH,self.frame_prf_0)
self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT,self.frame_prf_1)
self.capture.set(cv2.CAP_PROP_FPS,self.frame_rate)
self.view_x = int(self.frame_prf_0 * self.view_magnify)
self.view_y = int(self.frame_prf_1 * self.view_magnify)
except:
self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, 2592) # Force write frame size without using camera profile.
self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT,1944) # Force write frame size without using camera profile.
self.capture.set(cv2.CAP_PROP_FPS,5) # Force write frame size without using camera profile.
self.view_x = int(2592 * self.view_magnify)
self.view_y = int(1944 * self.view_magnify)
if self.view_y == 0.0:
aspect_ratio = self.view_width / self.view_height
else:
aspect_ratio = self.view_x / self.view_y
if self.view_x > self.view_width:
self.view_magnify = self.view_magnify*self.view_width/self.view_x
self.view_x = self.view_width
self.view_y = int(self.view_width / aspect_ratio)
if self.view_y > self.view_height:
self.view_magnify = self.view_magnify*self.view_height/self.view_y
self.view_y = self.view_height
self.view_x = int(self.view_height * aspect_ratio)
return
def Set_Objective_Lens(self,event):
name = self.combobox_1.get()
dictionary = {'x5':5.0, 'x10':10.0, 'x20':20.0, 'x50':50.0, 'x100':100.0}
self.str_lens_magnify = name
self.lens_magnify = dictionary[name]
return
def Set_Length(self,event):
name = self.combobox_2.get()
dictionary = {'10um':10.0, '20um':20.0, '50um':50.0, '100um':100.0, '200um':200.0,'500um':500.0,'1000um':1000.0}
self.str_length = name
self.length = dictionary[name]
return
def Set_Color(self,event):
name = self.combobox_3.get()
dictionary = {'white':self.white, 'green':self.green, 'aqua':self.aqua, 'black':self.black, 'red':self.red }
self.str_color = name
self.color = dictionary[name]
return
def Set_Config(self):
self.capture.set(cv2.CAP_PROP_SETTINGS,1)
#self.caputre.set(cv2.CAP_PROP_AUTO_EXPOSURE,3) #auto mode
#self.caputre.set(cv2.CAP_PROP_AUTO_EXPOSURE,1) #manual mode
#self.caputre.set(cv2.CAP_PROP_EXPOSURE,desired_exposure_value) #exposure_value ...0->1s -1->500ms,,-13->122.1us
return
# Show scale according to "On/Off" button.
def Show_Scale(self):
self.show_scale = not self.show_scale
return
if __name__ == "__main__":
root = tk.Tk()
app = Application(master = root)
app.mainloop()