CoolFace
Apppublic

pui8838/opencv_Image_processing

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py164 linesDownload Raw Back to root
1import cv2  2import gradio as gr  3import numpy as np  4 5 6def original_image(input_image):7    return input_image8 9def grayscale(input_image):10    gray_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)11    return gray_image12 13def edge_detection(input_image):14    edges = cv2.Canny(input_image, 100, 200)15    return edges16 17def sobel_edge_detection(input_image):18    gray_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)19    sobel_x = cv2.Sobel(gray_image, cv2.CV_64F, 1, 0, ksize=5)20    sobel_y = cv2.Sobel(gray_image, cv2.CV_64F, 0, 1, ksize=5)21    sobel_magnitude = cv2.magnitude(sobel_x, sobel_y)22    sobel_magnitude = np.uint8(255 * sobel_magnitude / np.max(sobel_magnitude))23    return sobel_magnitude24 25def invert_colors(input_image):26    inverted_image = cv2.bitwise_not(input_image)27    return inverted_image28 29def erosion(input_image, iterations):30    kernel = np.ones((5, 5), np.uint8)31    eroded_image = cv2.erode(input_image, kernel, iterations=iterations)32    return eroded_image33 34def dilation(input_image, dilation_iterations):35    kernel = np.ones((5, 5), np.uint8)36    dilated_image = cv2.dilate(input_image, kernel, iterations=dilation_iterations)37    return dilated_image38 39def gaussian_blur(image, blur_degree):40 41    blur_degree = int(blur_degree) | 1 42 43    result = cv2.GaussianBlur(image, (blur_degree, blur_degree), 0)44    45    return result46 47 48def custom_filter(input_image):49    kernel = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]])50    return cv2.filter2D(input_image, -1, kernel)51 52 53def mosaic(image, block_size):54    if image is None:55        return None56    57    height, width = image.shape[:2]58    for y in range(0, height, block_size):59        for x in range(0, width, block_size):60            # Define the region of interest (ROI), ensuring it doesn't go out of bounds61            roi = image[y:min(y + block_size, height), x:min(x + block_size, width)]62            63            # Compute the average color of the ROI64            color = np.mean(roi, axis=(0, 1)).astype(int)65            66            # Set the block region to the average color67            image[y:min(y + block_size, height), x:min(x + block_size, width)] = color68    69    return image70 71 72 73def apply_opencv_methods(input_image, method, iterations, blur_degree, dilation_iterations, mosaic_block_size):74    if method == "default":75        return original_image(input_image)76    elif method == "erosion":77        return erosion(input_image, iterations)78    elif method == "dilation":79        return dilation(input_image, dilation_iterations)80    elif method == "邊緣檢測1(Sobel)":81        return sobel_edge_detection(input_image)82    elif method == "風格變換":83        return custom_filter(input_image)84    elif method == "模糊":85        return gaussian_blur(input_image, blur_degree) 86    elif method == "馬賽克":87        return mosaic(input_image,mosaic_block_size)  88    else:89        methods = {90            "灰階": grayscale,91            "邊緣檢測2(Canny)": edge_detection,92            "反轉顏色": invert_colors,93        }94        return methods[method](input_image)95 96 97def update_slider_visibility(method):98    return (99        gr.update(visible=(method == "erosion")),100        gr.update(visible=(method == "模糊")),101        gr.update(visible=(method == "dilation")),102        gr.update(visible=(method == "馬賽克"))103    )104 105css="""106        @import url('https://fonts.googleapis.com/css2?family=LXGW+WenKai+TC&display=swap');107        108        .gradio-container {109            font-family: 'LXGW WenKai TC', sans-serif;  /* 將字體套用到整個 Gradio 介面 */110        }111        112        .gradio-container h1 {  /* 修改 title 標題樣式 */113            font-family: 'LXGW WenKai TC', sans-serif;  /* 字體 */114            font-size: 32px;  /* 字體大小 */115            color: #F5F5DC;  /* 字體顏色 */116            text-align: center;  /* 置中對齊 */117        }118    119        .dark-light-toggle {  /* 隱藏主題切換按鈕 */120            display: none !important;121        }122        """123 124with gr.Blocks(css=css) as demo:125    input_image = gr.Image(type="numpy", label="input image")126    method = gr.Radio(127        choices=["default", "灰階", "反轉顏色", "erosion", "dilation", "模糊", "馬賽克" ,"邊緣檢測1(Sobel)", "邊緣檢測2(Canny)", "風格變換"],128        value="default",129        label="選擇操作方法")130    iterations = gr.Slider(minimum=0, maximum=10, step=1, value=1, label="參數大小", visible=False)131    blur_degree = gr.Slider(minimum=1, maximum=25, step=2, value=1, label="模糊程度", visible=False)132    dilation_iterations = gr.Slider(minimum=0, maximum=10, step=1, value=1, label="參數大小", visible=False)133    mosaic_block_size = gr.Slider(minimum=5, maximum=50, step=5, value=5, label="馬賽克塊大小", visible=False)134    output_image = gr.Image(type="numpy", label="output image")135 136    137 138    method.change(139        fn=update_slider_visibility,140        inputs=[method],141        outputs=[iterations, blur_degree, dilation_iterations, mosaic_block_size]142    )143 144    gr.Interface(145        fn=apply_opencv_methods,146        inputs=[input_image, method, iterations, blur_degree, dilation_iterations, mosaic_block_size],147        outputs=output_image,148        live=True,149        title="各種影像處理",150        description="上傳一張圖片並選擇想要處理影像的方法",151        152    )153    154    examples = gr.Examples(155        examples=[156            ["chikawa.jpg", "erosion", 2, None, None, None],157            ["cat.jpg", "風格變換", None, None, None, None],158            ["pui.jpg", "模糊", None, 15, None, None]159        ],160        inputs=[input_image, method, iterations, blur_degree, dilation_iterations, mosaic_block_size],161        label="example",162    )163 164demo.launch()