| | import gradio as gr |
| | import cv2 |
| | import numpy as np |
| |
|
| | |
| | def edge_detection(image, threshold1, threshold2): |
| | gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) |
| | edges = cv2.Canny(gray_image, threshold1, threshold2) |
| | return edges |
| |
|
| | |
| | def image_segmentation(image, compactness): |
| | from skimage.segmentation import slic |
| | from skimage import color |
| | segments = slic(image, compactness=compactness, n_segments=200) |
| | return color.label2rgb(segments, image, kind='avg') |
| |
|
| | |
| | def adjust_color(image, r_min, r_max, g_min, g_max, b_min, b_max): |
| | |
| | if image.shape[-1] == 4: |
| | image = cv2.cvtColor(image, cv2.COLOR_RGBA2RGB) |
| | |
| | |
| | image = image.astype(np.float32) |
| | image[:, :, 0] = np.clip(image[:, :, 0], r_min, r_max) |
| | image[:, :, 1] = np.clip(image[:, :, 1], g_min, g_max) |
| | image[:, :, 2] = np.clip(image[:, :, 2], b_min, b_max) |
| | image = image.astype(np.uint8) |
| | |
| | return image |
| |
|
| | |
| | def app(): |
| | with gr.Blocks() as demo: |
| | gr.Markdown("# 影像處理功能展示") |
| | gr.Markdown("本應用程式展示了使用 OpenCV 實現的影像處理功能,包括動態調整 RGB 範圍的功能。") |
| | |
| | with gr.Tab("邊緣檢測"): |
| | with gr.Row(): |
| | input_image = gr.Image(label="輸入圖片") |
| | edge_result = gr.Image(label="邊緣檢測結果") |
| | with gr.Row(): |
| | threshold1 = gr.Slider(0, 255, value=100, step=1, label="閾值1") |
| | threshold2 = gr.Slider(0, 255, value=200, step=1, label="閾值2") |
| | edge_button = gr.Button("執行邊緣檢測") |
| | edge_button.click( |
| | fn=edge_detection, |
| | inputs=[input_image, threshold1, threshold2], |
| | outputs=edge_result |
| | ) |
| | |
| | with gr.Tab("圖像分割"): |
| | with gr.Row(): |
| | input_image = gr.Image(label="輸入圖片") |
| | seg_result = gr.Image(label="分割結果") |
| | with gr.Row(): |
| | compactness = gr.Slider(0.1, 100, value=10, step=0.1, label="分割緊湊度") |
| | seg_button = gr.Button("執行圖像分割") |
| | seg_button.click( |
| | fn=image_segmentation, |
| | inputs=[input_image, compactness], |
| | outputs=seg_result |
| | ) |
| | |
| | with gr.Tab("顏色範圍調整"): |
| | with gr.Row(): |
| | input_image = gr.Image(label="輸入圖片") |
| | adjusted_result = gr.Image(label="調整後的圖片") |
| | with gr.Row(): |
| | r_min = gr.Slider(0, 255, value=0, step=1, label="R 最小值") |
| | r_max = gr.Slider(0, 255, value=255, step=1, label="R 最大值") |
| | g_min = gr.Slider(0, 255, value=0, step=1, label="G 最小值") |
| | g_max = gr.Slider(0, 255, value=255, step=1, label="G 最大值") |
| | b_min = gr.Slider(0, 255, value=0, step=1, label="B 最小值") |
| | b_max = gr.Slider(0, 255, value=255, step=1, label="B 最大值") |
| | adjust_button = gr.Button("調整顏色範圍") |
| | adjust_button.click( |
| | fn=adjust_color, |
| | inputs=[input_image, r_min, r_max, g_min, g_max, b_min, b_max], |
| | outputs=adjusted_result |
| | ) |
| | |
| | return demo |
| |
|
| | |
| | if __name__ == "__main__": |
| | app().launch() |
| |
|