import gradio as gr import cv2 import numpy as np from skimage import io, segmentation # 功能函數 def image_segmentation(image): segments = segmentation.slic(image, n_segments=100, compactness=10) return segmentation.mark_boundaries(image, segments) def edge_detection(image, threshold1, threshold2): edges = cv2.Canny(image, threshold1, threshold2) return edges def image_inpainting(image, mask): # 確保影像和遮罩有相同的尺寸 if image.shape[:2] != mask.shape[:2]: raise ValueError("影像和遮罩的尺寸不一致!") # 將遮罩轉換為單通道(灰度) if len(mask.shape) == 3: mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY) # 修復影像 inpainted = cv2.inpaint(image, mask, inpaintRadius=3, flags=cv2.INPAINT_TELEA) return inpainted def template_matching(image, template): result = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result) matched_image = image.copy() h, w = template.shape[:2] cv2.rectangle(matched_image, max_loc, (max_loc[0] + w, max_loc[1] + h), (0, 255, 0), 2) return matched_image # Gradio 介面設置 def app_interface(): with gr.Blocks() as demo: gr.Markdown("## 電腦視覺功能展示") with gr.Tabs(): # 分割功能 with gr.Tab("影像分割"): image_input = gr.Image(label="上傳影像", type="numpy") seg_output = gr.Image(label="分割後影像") seg_button = gr.Button("執行分割") seg_button.click(image_segmentation, inputs=[image_input], outputs=[seg_output]) # 邊緣偵測 with gr.Tab("邊緣偵測"): edge_input = gr.Image(label="上傳影像", type="numpy") thresh1 = gr.Slider(0, 255, value=100, step=1, label="閾值 1") thresh2 = gr.Slider(0, 255, value=200, step=1, label="閾值 2") edge_output = gr.Image(label="邊緣偵測結果") edge_button = gr.Button("執行邊緣偵測") edge_button.click(edge_detection, inputs=[edge_input, thresh1, thresh2], outputs=[edge_output]) # 影像修復 with gr.Tab("影像修復"): # 輸入影像與遮罩 inpaint_input = gr.Image(label="上傳影像", type="numpy") mask_input = gr.Image(label="上傳遮罩 (白色為修復區域)", type="numpy") # 輸出修復後影像 inpaint_output = gr.Image(label="修復後影像") # 按鈕操作 inpaint_button = gr.Button("執行修復") # 綁定影像修復函數到按鈕 inpaint_button.click(image_inpainting, inputs=[inpaint_input, mask_input], outputs=inpaint_output) # 模板匹配 with gr.Tab("模板匹配"): match_input = gr.Image(label="上傳影像", type="numpy") template_input = gr.Image(label="上傳模板", type="numpy") match_output = gr.Image(label="模板匹配結果") match_button = gr.Button("執行匹配") match_button.click(template_matching, inputs=[match_input, template_input], outputs=[match_output]) return demo demo = app_interface() demo.launch()