import gradio as gr import cv2 import numpy as np def segment_image(image, spatial_radius=20, color_radius=30): segmented = cv2.pyrMeanShiftFiltering(image, spatial_radius, color_radius) return segmented def edge_detection(image, threshold1=100, threshold2=200): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, threshold1, threshold2) return edges def edge_detection_interface(image, threshold1, threshold2): image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # Gradio 輸入為 RGB edges = edge_detection(image, threshold1, threshold2) return edges def segmentation_interface(image, spatial_radius, color_radius): image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) segmented = segment_image(image, spatial_radius, color_radius) return cv2.cvtColor(segmented, cv2.COLOR_BGR2RGB) # 範例影像的路徑 example_images = [ ["example/girl.jpeg"], # 確保路徑正確,並且是圖片文件 ["example/sea.jpeg"] ] with gr.Blocks() as demo: gr.Markdown("### OpenCV 基本影像處理工具") with gr.Tab("邊緣檢測"): with gr.Row(): input_image = gr.Image(label="上傳影像") output_image = gr.Image(label="結果影像") with gr.Row(): threshold1_slider = gr.Slider(0, 255, value=100, label="弱邊緣檢測閾值 (低)") threshold2_slider = gr.Slider(0, 255, value=200, label="強邊緣檢測閾值 (高)") edge_button = gr.Button("執行") edge_button.click(edge_detection_interface, inputs=[input_image, threshold1_slider, threshold2_slider], outputs=output_image) # 範例影像按鈕 gr.Examples( examples=example_images, inputs=input_image, outputs=output_image, fn=lambda x: x, # 這裡可以處理或修改影像處理方法 label="範例影像" ) with gr.Tab("影像分割"): with gr.Row(): input_image_seg = gr.Image(label="上傳影像") output_image_seg = gr.Image(label="結果影像") with gr.Row(): spatial_slider = gr.Slider(1, 50, value=20, label="Spatial Radius") color_slider = gr.Slider(1, 50, value=30, label="Color Radius") segment_button = gr.Button("執行") segment_button.click(segmentation_interface, inputs=[input_image_seg, spatial_slider, color_slider], outputs=output_image_seg) # 範例影像按鈕 gr.Examples( examples=example_images, inputs=input_image_seg, outputs=output_image_seg, fn=lambda x: x, # 這裡可以處理或修改影像處理方法 label="範例影像" ) # 啟動介面 if __name__ == "__main__": demo.launch()