Skip to content

Commit e16c867

Browse files
committed
add show origin image button and fix some bugs
1 parent 274cc5c commit e16c867

File tree

5 files changed

+82
-30
lines changed

5 files changed

+82
-30
lines changed

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,5 @@
22
pretrained/*.pb
33
__pycache__
44
.DS_Store/
5+
dist/
6+
build/

app.py

+65-24
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ def __init__(self):
3737
self.frame_main_left = None
3838
self.frame_main_center = None
3939
self.frame_main_right = None
40+
self.show_origin_btn = None
41+
self.show_enhanced_btn = None
4042
self.canvas: ResizingCanvas = None
4143
self.enhance_pb = None
4244
self.start_enhance_btn = None
@@ -83,9 +85,26 @@ class ThemedStyle:
8385
self.model_dir = resource_path("pretrained/")
8486
self.vignette_handler()
8587

86-
def enhance_listener(self, *args):
87-
if not (self._check_image() and self._check_model()):
88+
def _show_origin_listener(self, *args):
89+
if not (self._check_image()): return
90+
image = Image.fromarray(np.asarray(self._main_image_origin))
91+
self.canvas.set_main_image(image)
92+
self.show_origin_btn.config(state="disabled")
93+
self.show_enhanced_btn.config(state="normal")
94+
95+
def _show_enhanced_listener(self, *args):
96+
if not (self._check_image()): return
97+
if self._main_image_enhanced is None:
98+
pop_msg.showinfo("Umm...", "請先增強圖片")
8899
return
100+
image = Image.fromarray(np.asarray(self._main_image_enhanced))
101+
self.canvas.set_main_image(image)
102+
self.canvas.request_update()
103+
self.show_enhanced_btn.config(state="disabled")
104+
self.show_origin_btn.config(state="normal")
105+
106+
def enhance_listener(self, *args):
107+
if not (self._check_image() and self._check_model()): return
89108
thread = td.Thread(target=self._enhance_task)
90109
self.status_text.set("增強圖片中..")
91110
self.enhance_pb.start()
@@ -114,8 +133,7 @@ def _resize_height_listener(self, *args):
114133
def _resize_width_listener(self, *args):
115134
if not self._check_image(): return
116135
with self.resize_lock:
117-
if self.resizing:
118-
return
136+
if self.resizing: return
119137
self.resizing = True
120138
origin_height, origin_width, _ = np.shape(self._main_image_origin)
121139
resize_width = 0 if not self.resize_width.get() else int(self.resize_width.get())
@@ -133,9 +151,11 @@ def _enhance_task(self):
133151

134152
resize_image = cv2.resize(self._main_image_origin, dsize=(new_width, new_height))
135153
resize_image = resize_image[new_height % 8:, new_width % 8:, :]
136-
self._main_image_enhanced = self._model.sample(resize_image, denoise=False)
137-
self._main_image_current_clean = self._main_image_enhanced
138-
print(self._main_image_enhanced)
154+
enhance_result = self._model.sample(resize_image, denoise=False)
155+
if enhance_result is not None:
156+
self._main_image_enhanced = enhance_result
157+
self._main_image_current_clean = self._main_image_enhanced
158+
139159

140160
def _enhance_handler(self, thread: td.Thread):
141161
if thread.is_alive():
@@ -144,27 +164,42 @@ def _enhance_handler(self, thread: td.Thread):
144164
self.enhance_pb.stop()
145165
self.start_enhance_btn.config(state="normal")
146166
self.config(cursor='')
147-
image = Image.fromarray(np.asarray(self._main_image_enhanced))
148-
self.canvas.set_main_image(image)
149-
self.canvas.request_update()
150-
self.status_text.set("處理完成!")
151-
try:
152-
subprocess.check_output(["notify-send", "圖片處理完成!", "<b>幻想濾鏡™</b>處理好圖片囉!", "--icon=face-glasses"])
153-
except FileNotFoundError:
154-
print("can't send notification.")
155-
self.after(3000, lambda: self.status_text.set("就緒"))
167+
if self._model.success:
168+
self.show_enhanced_btn.config(state="disabled")
169+
self.show_origin_btn.config(state="normal")
170+
image = Image.fromarray(np.asarray(self._main_image_enhanced))
171+
self.canvas.set_main_image(image)
172+
self.canvas.request_update()
173+
self.status_text.set("處理完成!")
174+
try:
175+
subprocess.check_output(["notify-send", "圖片處理完成!", "<b>幻想濾鏡™</b>處理好圖片囉!", "--icon=face-glasses"])
176+
except:
177+
logging.warning("can't send notification.")
178+
self.after(3000, lambda: self.status_text.set("就緒"))
179+
180+
else:
181+
pop_msg.showerror("Something went wrong.. ", "圖片處理失敗!\n多數失敗是由於圖片太大張了,把圖片縮小點試試~")
182+
pop_msg.showerror("Something went wrong.. ", self._model.error_log)
183+
184+
self.status_text.set("處理失敗!")
185+
try:
186+
subprocess.check_output(["notify-send", "圖片處理失敗!", "<b>幻想濾鏡™</b>圖片處理失敗了QQ", "--icon=face-sad"])
187+
except:
188+
logging.warning("can't send notification.")
189+
190+
self.after(3000, lambda: self.status_text.set("就緒"))
156191

157192
def open_image_listener(self, *args):
158193

159194
try:
195+
# for Linux
160196
filename = subprocess.check_output(['zenity', '--file-selection']).decode("utf-8").strip()
161197
except FileNotFoundError:
162198
filename = filedialog.askopenfilename()
163199
except subprocess.CalledProcessError:
164200
filename = False
165201

166202
if not filename:
167-
logging.info("cancel opening image.")
168203
return False
169204
try:
170205
logging.info("open image:", filename)
@@ -178,8 +213,6 @@ def open_image_listener(self, *args):
178213
self.resize_height.set(image.height)
179214
self.resize_width.set(image.width)
180215

181-
182-
183216
except IOError as e:
184217
logging.error("open image failed!")
185218
logging.error(str(e))
@@ -266,9 +299,14 @@ def save(self, *args):
266299
image.save(path)
267300

268301
def run(self):
269-
302+
'''
303+
try:
304+
# self.call('wm', 'iconphoto', self._w, ImageTk.PhotoImage(Image.open(resource_path('appicon.png'))))
305+
self.iconbitmap(resource_path('appicon.ico'))
306+
except:
307+
pass
308+
'''
270309
self.title("Fantastic Filter")
271-
272310
self.geometry("%dx%d+50+40" % (800, 500))
273311

274312
"""
@@ -307,6 +345,10 @@ def run(self):
307345
model_cbb.current(0) # 選擇第一個
308346
model_cbb.bind("<<ComboboxSelected>>", self.select_model_listener) # 绑定事件,(下拉列表框被选中时)
309347

348+
self.show_origin_btn = ttk.Button(frame_toolbar, text="檢視原圖", command=self._show_origin_listener)
349+
self.show_enhanced_btn = ttk.Button(frame_toolbar, text="檢視增強後", command=self._show_enhanced_listener)
350+
self.show_origin_btn.pack(side='left', padx=(10, 0))
351+
self.show_enhanced_btn.pack(side='left', padx=(0, 10))
310352
''' main area '''
311353

312354
# split into 3 part, | load _model,image... | image preview | edit.. save.|
@@ -348,8 +390,8 @@ def run(self):
348390
validatecommand=(self.register(isnumeric_or_blank), "%P"), width=9)
349391
self.input_resize_width = ttk.Entry(frame_resize_inputs, textvariable=self.resize_width, validate='key',
350392
validatecommand=(self.register(isnumeric_or_blank), "%P"), width=9)
351-
self.input_resize_width.pack(side='left')
352-
self.input_resize_height.pack(side='right')
393+
self.input_resize_width.pack(side='left', padx=(0, 4))
394+
self.input_resize_height.pack(side='right', padx=(4, 0))
353395

354396
ttk.Separator(self.frame_main_right, orient='horizontal').pack(fill='x', pady=10)
355397

@@ -509,7 +551,6 @@ def set_main_image(self, image: Image):
509551

510552
def resource_path(relative_path):
511553
if hasattr(sys, '_MEIPASS'):
512-
print(sys._MEIPASS)
513554
return sys._MEIPASS + '/' + relative_path
514555
return os.path.join(os.path.dirname(os.path.abspath(__file__)), relative_path)
515556

app.spec

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@ block_cipher = None
44

55

66
a = Analysis(['app.py'],
7-
pathex=['/home/ray1422/workspace/Fantasic-Filter'],
7+
pathex=['./Fantasic-Filter'],
88
binaries=[],
9-
datas=[('venv//Lib//site-packages//ttkthemes', 'ttkthemes')],
9+
datas=[('venv//Lib//site-packages//ttkthemes', 'ttkthemes'), ('./appicon.png', 'appicon.png'), ('./appicon.ico', ''appicon.ico'')],
1010
hiddenimports=['ttkthemes'],
1111
hookspath=[],
1212
runtime_hooks=[],

appicon.ico

9 KB
Binary file not shown.

enhancer.py

+13-4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import logging
12
import os
23

34
import cv2
@@ -15,6 +16,8 @@ def __init__(self, gpu=True):
1516
self._graph = _Graph()
1617
self._result = []
1718
self._available = True
19+
self.success = False
20+
self.error_log = ''
1821
self.model_available = lambda: self._sess is not None
1922
if not gpu:
2023
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
@@ -109,10 +112,12 @@ def batch_process(self):
109112

110113
result_img = cv2.cvtColor(result_img, cv2.COLOR_RGB2BGR)
111114
cv2.imwrite(save_path, result_img)
115+
self.success = True
112116

113117
except Exception as e:
114118
print("Something went wrong!")
115119
print(str(e))
120+
self.success = False
116121

117122
self._available = True
118123

@@ -135,12 +140,16 @@ def sample(self, image, denoise=False, denoise_after=False):
135140

136141
if denoise_after:
137142
result_img = cv2.fastNlMeansDenoisingColored(result_img, None, 10, 10, 5, 5)
138-
143+
self.error_log = ''
144+
self.success = True
139145
return result_img
140146
except Exception as e:
141-
print("Something went wrong!")
142-
print(str(e))
143-
return np.zeros_like(image)
147+
logging.error("Something went during enhancing task :(")
148+
logging.error("It should caused by TensorFlow.")
149+
logging.error(str(e))
150+
self.success = False
151+
self.error_log = str(e)
152+
return None
144153

145154
finally:
146155
self._available = True

0 commit comments

Comments
 (0)