Spaces:
Sleeping
Sleeping
Download app.py from Besimplestudio/im2skch: direct link, hf CLI and curl.
- Browser
- Download file 1.97 kB
-
https://huggingface.co/spaces/Besimplestudio/im2skch/resolve/main/app.py
- Command line
-
hf download hf://spaces/Besimplestudio/im2skch/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Besimplestudio/im2skch/resolve/main/app.py
1.97 kB
| import gradio as gr | |
| import cv2 | |
| import numpy as np | |
| from PIL import Image, ImageEnhance | |
| def pil_to_cv2(img): | |
| return cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR) | |
| def cv2_to_pil(img): | |
| if len(img.shape) == 2: # grayscale | |
| return Image.fromarray(img) | |
| else: | |
| return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) | |
| def convert_to_sketch(img, quality=15, contrast=1.0, brightness=1.0): | |
| # Convert PIL to OpenCV format | |
| img_cv = pil_to_cv2(img) | |
| # Adjust contrast and brightness using PIL for better quality | |
| img_pil = Image.fromarray(cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB)) | |
| enhancer_contrast = ImageEnhance.Contrast(img_pil) | |
| img_pil = enhancer_contrast.enhance(contrast) | |
| enhancer_brightness = ImageEnhance.Brightness(img_pil) | |
| img_pil = enhancer_brightness.enhance(brightness) | |
| img_cv = cv2.cvtColor(np.array(img_pil), cv2.COLOR_RGB2BGR) | |
| # Convert to grayscale | |
| gray = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY) | |
| # Invert grayscale | |
| inv = 255 - gray | |
| # Apply Gaussian blur | |
| blur = cv2.GaussianBlur(inv, (0, 0), sigmaX=quality, sigmaY=quality) | |
| # Dodge blend: division of gray by inverted blur image | |
| sketch = cv2.divide(gray, 255 - blur, scale=256) | |
| # Return as PIL image for Gradio output | |
| return cv2_to_pil(sketch) | |
| iface = gr.Interface( | |
| fn=convert_to_sketch, | |
| inputs=[ | |
| gr.Image(type="pil", label="Upload Image"), | |
| gr.Slider(minimum=1, maximum=50, value=15, step=1, label="Adjust Quality"), | |
| gr.Slider(minimum=0.5, maximum=2.0, value=1.0, step=0.1, label="Adjust Contrast"), | |
| gr.Slider(minimum=0.5, maximum=2.0, value=1.0, step=0.1, label="Adjust Brightness"), | |
| ], | |
| outputs=gr.Image(type="pil", label="Sketch Output"), | |
| title="Image to Sketch Converter", | |
| description="Upload an image and adjust quality, contrast, and brightness to convert it into a pencil sketch." | |
| ) | |
| if __name__ == "__main__": | |
| iface.launch() | |