Update app.py
Browse files
app.py
CHANGED
|
@@ -18,25 +18,29 @@ def image_segmentation(image, compactness):
|
|
| 18 |
|
| 19 |
# 圖像修復函式
|
| 20 |
def inpaint_image(image, mask_threshold):
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
image
|
| 24 |
-
|
| 25 |
-
image
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
# 主應用程式
|
| 42 |
def app():
|
|
@@ -74,19 +78,18 @@ def app():
|
|
| 74 |
with gr.Tab("圖像修復"):
|
| 75 |
with gr.Row():
|
| 76 |
input_image = gr.Image(label="輸入圖片")
|
| 77 |
-
inpaint_result = gr.Image(label="
|
| 78 |
with gr.Row():
|
| 79 |
mask_threshold = gr.Slider(0, 255, value=128, step=1, label="遮罩閾值")
|
| 80 |
inpaint_button = gr.Button("執行圖像修復")
|
| 81 |
inpaint_button.click(
|
| 82 |
fn=inpaint_image,
|
| 83 |
inputs=[input_image, mask_threshold],
|
| 84 |
-
outputs=inpaint_result
|
| 85 |
-
show_error=True # 在 UI 上顯示錯誤訊息
|
| 86 |
)
|
| 87 |
|
| 88 |
return demo
|
| 89 |
|
| 90 |
# 啟動應用程式
|
| 91 |
if __name__ == "__main__":
|
| 92 |
-
app().launch()
|
|
|
|
| 18 |
|
| 19 |
# 圖像修復函式
|
| 20 |
def inpaint_image(image, mask_threshold):
|
| 21 |
+
try:
|
| 22 |
+
# 確保圖片格式為 RGB
|
| 23 |
+
if image.shape[-1] == 4: # 如果圖片有 alpha 通道
|
| 24 |
+
image = cv2.cvtColor(image, cv2.COLOR_RGBA2RGB)
|
| 25 |
+
elif image.shape[-1] == 3:
|
| 26 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
| 27 |
+
|
| 28 |
+
# 轉為灰階圖片
|
| 29 |
+
gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
|
| 30 |
+
# 根據遮罩閾值生成遮罩
|
| 31 |
+
_, mask = cv2.threshold(gray_image, mask_threshold, 255, cv2.THRESH_BINARY)
|
| 32 |
+
mask = mask.astype(bool)
|
| 33 |
+
|
| 34 |
+
# 如果遮罩無效,拋出錯誤
|
| 35 |
+
if not mask.any():
|
| 36 |
+
return "遮罩生成失敗,請調整遮罩閾值參數。"
|
| 37 |
+
|
| 38 |
+
# 使用 biharmonic 方法修復圖像
|
| 39 |
+
inpainted = inpaint.inpaint_biharmonic(image, mask, multichannel=True)
|
| 40 |
+
return inpainted
|
| 41 |
+
except Exception as e:
|
| 42 |
+
# 如果發生錯誤,返回錯誤訊息
|
| 43 |
+
return f"發生錯誤:{str(e)}"
|
| 44 |
|
| 45 |
# 主應用程式
|
| 46 |
def app():
|
|
|
|
| 78 |
with gr.Tab("圖像修復"):
|
| 79 |
with gr.Row():
|
| 80 |
input_image = gr.Image(label="輸入圖片")
|
| 81 |
+
inpaint_result = gr.Image(label="修復結果或錯誤訊息")
|
| 82 |
with gr.Row():
|
| 83 |
mask_threshold = gr.Slider(0, 255, value=128, step=1, label="遮罩閾值")
|
| 84 |
inpaint_button = gr.Button("執行圖像修復")
|
| 85 |
inpaint_button.click(
|
| 86 |
fn=inpaint_image,
|
| 87 |
inputs=[input_image, mask_threshold],
|
| 88 |
+
outputs=inpaint_result # 錯誤訊息或結果會顯示在此
|
|
|
|
| 89 |
)
|
| 90 |
|
| 91 |
return demo
|
| 92 |
|
| 93 |
# 啟動應用程式
|
| 94 |
if __name__ == "__main__":
|
| 95 |
+
app().launch()
|