dschandra commited on
Commit
1c34990
·
verified ·
1 Parent(s): c1a5f36

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -75
app.py CHANGED
@@ -1,90 +1,90 @@
1
- # app_colab.py
2
  import cv2
3
  import numpy as np
4
- import matplotlib.pyplot as plt
5
- from IPython.display import clear_output
6
- import imageio
7
 
8
- def load_image(image_path, scale_percent=50):
9
- """Load and resize image"""
10
- img = cv2.imread(image_path)
11
- if img is None:
12
- raise FileNotFoundError(f"Image not found: {image_path}")
13
-
14
- width = int(img.shape[1] * scale_percent / 100)
15
- height = int(img.shape[0] * scale_percent / 100)
16
- img = cv2.resize(img, (width, height))
17
- return img
18
-
19
- def pencil_sketch(img, blur_ksize=21):
20
- """Convert image to pencil sketch"""
21
- gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
22
- inv_gray = 255 - gray
23
- blur = cv2.GaussianBlur(inv_gray, (blur_ksize, blur_ksize), 0)
24
- sketch = cv2.divide(gray, 255 - blur, scale=256)
25
- return sketch
26
 
27
- def add_texture(sketch, intensity=15):
28
- """Add pencil texture to sketch"""
29
- noise = np.random.normal(0, intensity, sketch.shape).astype(np.uint8)
30
- sketch_textured = cv2.add(sketch, noise)
31
- return sketch_textured
32
 
33
- def animate_sketch(sketch, save_gif=False, gif_name="pencil_sketch_animation.gif", show_animation=True):
34
- """Animate sketch line by line"""
35
- canvas = np.ones_like(sketch) * 255
36
- y_indices, x_indices = np.where(sketch < 255)
37
- coords = list(zip(x_indices, y_indices))
38
- coords.sort(key=lambda pt: sketch[pt[1], pt[0]]) # draw dark pixels first
39
 
40
- frames = []
41
- for i, (x, y) in enumerate(coords):
42
- canvas[y, x] = sketch[y, x]
43
- if i % 200 == 0:
44
- if show_animation:
45
- clear_output(wait=True)
46
- plt.imshow(canvas, cmap='gray')
47
- plt.axis('off')
48
- plt.show()
49
- if save_gif:
50
- frames.append(canvas.copy())
51
 
52
- # Final frame
53
- if show_animation:
54
- clear_output(wait=True)
55
- plt.imshow(canvas, cmap='gray')
56
- plt.axis('off')
57
- plt.show()
58
 
59
- if save_gif:
60
- imageio.mimsave(gif_name, frames, duration=0.05)
61
- print(f"[INFO] GIF saved as {gif_name}")
62
 
63
- return canvas
 
 
64
 
65
- # -----------------------------
66
- # Colab Usage Example
67
- # -----------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
- # 1️⃣ Upload your image in Colab:
70
- from google.colab import files
71
- uploaded = files.upload()
72
- image_path = list(uploaded.keys())[0] # take the first uploaded file
73
 
74
- # 2️⃣ Load the image
75
- img = load_image(image_path, scale_percent=50)
76
- plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
77
- plt.axis('off')
78
- plt.title("Original Image")
79
- plt.show()
80
 
81
- # 3️⃣ Convert to pencil sketch
82
- sketch = pencil_sketch(img, blur_ksize=21)
 
 
 
 
 
 
 
83
 
84
- # 4️⃣ Add pencil texture
85
- sketch_textured = add_texture(sketch, intensity=15)
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- # 5️⃣ Animate and save as GIF
88
- final_canvas = animate_sketch(sketch_textured, save_gif=True)
89
- cv2.imwrite("final_sketch.png", final_canvas)
90
- print("[INFO] Final sketch saved as final_sketch.png")
 
 
1
  import cv2
2
  import numpy as np
3
+ import gradio as gr
4
+ import time
 
5
 
6
+ # ----------------------------
7
+ # Sketch Conversion Functions
8
+ # ----------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ def dodgeV2(image, mask):
11
+ """Helper function for pencil sketch effect"""
12
+ return cv2.divide(image, 255 - mask, scale=256)
 
 
13
 
14
+ def pencil_sketch(img, scale=256, blur_value=21, texture=False):
15
+ """Convert image to realistic pencil sketch"""
16
+ # Convert to grayscale
17
+ gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
 
 
18
 
19
+ # Invert image
20
+ inv_gray = 255 - gray_img
21
+
22
+ # Apply Gaussian blur
23
+ blur_img = cv2.GaussianBlur(inv_gray, (blur_value, blur_value), 0)
24
+
25
+ # Blend using dodge technique
26
+ sketch = dodgeV2(gray_img, blur_img)
 
 
 
27
 
28
+ # Optional: Add paper texture
29
+ if texture:
30
+ h, w = sketch.shape
31
+ paper = np.random.normal(loc=200, scale=30, size=(h, w)).astype(np.uint8)
32
+ sketch = cv2.multiply(sketch, paper, scale=1/255)
 
33
 
34
+ return sketch
 
 
35
 
36
+ # ----------------------------
37
+ # Animation Function
38
+ # ----------------------------
39
 
40
+ def animate_sketch(image, scale=256, blur=21, texture=False, delay=0.01):
41
+ """Simulate hand-drawn line-by-line animation"""
42
+ img = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
43
+ sketch = pencil_sketch(img, scale=scale, blur_value=blur, texture=texture)
44
+
45
+ # Create blank canvas
46
+ h, w = sketch.shape
47
+ canvas = np.ones((h, w), dtype=np.uint8) * 255
48
+
49
+ frames = []
50
+ for i in range(h):
51
+ canvas[i] = sketch[i] # Draw line by line
52
+ frame_rgb = cv2.cvtColor(canvas, cv2.COLOR_GRAY2RGB)
53
+ frames.append(frame_rgb)
54
+
55
+ return frames
56
 
57
+ # ----------------------------
58
+ # Gradio Interface
59
+ # ----------------------------
 
60
 
61
+ def gradio_sketch(image, scale, blur, texture):
62
+ frames = animate_sketch(image, scale, blur, texture)
63
+ return frames # Gradio will display as GIF automatically
 
 
 
64
 
65
+ # Gradio UI
66
+ title = "🎨 Realistic Pencil Sketch Animation"
67
+ description = """
68
+ Upload any image and watch it transform into a realistic pencil sketch with hand-drawn animation!
69
+ You can adjust:
70
+ - Scale: pencil intensity
71
+ - Blur: smoothness of strokes
72
+ - Texture: add paper texture
73
+ """
74
 
75
+ iface = gr.Interface(
76
+ fn=gradio_sketch,
77
+ inputs=[
78
+ gr.Image(type="pil", label="Upload Image"),
79
+ gr.Slider(64, 512, value=256, step=1, label="Scale"),
80
+ gr.Slider(1, 51, value=21, step=2, label="Blur"),
81
+ gr.Checkbox(label="Add Paper Texture?")
82
+ ],
83
+ outputs=gr.Gallery(label="Animated Sketch"),
84
+ title=title,
85
+ description=description,
86
+ allow_flagging="never",
87
+ )
88
 
89
+ if __name__ == "__main__":
90
+ iface.launch()