Spaces:
				
			
			
	
			
			
		Sleeping
		
	
	
	
			
			
	
	
	
	
		
		
		Sleeping
		
	| import gradio as gr | |
| from skimage import filters, color | |
| import numpy as np | |
| import cv2 | |
| # 邊緣檢測函數 | |
| def edge_detection(image, threshold1, threshold2, method): | |
| if method == "Canny (OpenCV)": | |
| edges = cv2.Canny(image, threshold1, threshold2) | |
| elif method == "Sobel (skimage)": | |
| gray = color.rgb2gray(image) if len(image.shape) == 3 else image | |
| edges = filters.sobel(gray) | |
| edges = (edges * 255).astype(np.uint8) # 轉換為 0-255 範圍 | |
| else: | |
| raise ValueError("Unknown method selected.") | |
| return edges | |
| # 動態更新閾值參數的顯示狀態 | |
| def update_threshold_visibility(method): | |
| if method == "Canny (OpenCV)": | |
| return gr.update(visible=True), gr.update(visible=True) | |
| else: | |
| return gr.update(visible=False), gr.update(visible=False) | |
| # 設定 Gradio UI | |
| def main(): | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# Edge Detection App") | |
| gr.Markdown("### Upload an image or select an example to detect edges.") | |
| with gr.Row(): | |
| with gr.Column(): | |
| input_image = gr.Image(label="Input Image", type="numpy") | |
| method = gr.Radio( | |
| ["Canny (OpenCV)", "Sobel (skimage)"], | |
| value="Canny (OpenCV)", | |
| label="Edge Detection Method" | |
| ) | |
| low_threshold = gr.Slider(0, 255, value=100, step=1, label="Low Threshold", visible=True) | |
| high_threshold = gr.Slider(0, 255, value=200, step=1, label="High Threshold", visible=True) | |
| with gr.Column(): | |
| output_image = gr.Image(label="Output Image") | |
| # 示例圖片與參數 | |
| examples = gr.Examples( | |
| examples=[ | |
| ["lenna.png", "Canny (OpenCV)", 100, 200], | |
| ["coin.png", "Sobel (skimage)", 0, 0], | |
| ["flower.png", "Canny (OpenCV)", 50, 150], | |
| ], | |
| inputs=[input_image, method, low_threshold, high_threshold], | |
| ) | |
| # 動態更新閾值參數的顯示 | |
| method.change( | |
| update_threshold_visibility, | |
| inputs=[method], | |
| outputs=[low_threshold, high_threshold] | |
| ) | |
| # 自動執行邊緣檢測 | |
| input_image.change( | |
| edge_detection, | |
| inputs=[input_image, low_threshold, high_threshold, method], | |
| outputs=[output_image] | |
| ) | |
| # 手動按鈕執行(備選方式) | |
| submit_btn = gr.Button("Detect Edges") | |
| submit_btn.click( | |
| edge_detection, | |
| inputs=[input_image, low_threshold, high_threshold, method], | |
| outputs=[output_image] | |
| ) | |
| return demo | |
| # 啟動應用 | |
| if __name__ == "__main__": | |
| app = main() | |
| app.launch(server_name="0.0.0.0", server_port=7860) | |
