Skip to content

Commit 80df592

Browse files
committed
differences for PR #328
1 parent e291be7 commit 80df592

File tree

3 files changed

+164
-0
lines changed

3 files changed

+164
-0
lines changed

data/letterA.tif

1.11 KB
Binary file not shown.

fig/blur-demo.gif

-30.6 MB
Loading
Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
### METADATA
2+
# author: Marco Dalla Vecchia @marcodallavecchia
3+
# description: Simple blurring animation of simple image
4+
# data-source: letterA.tif was created using ImageJ (https://imagej.net/ij/)
5+
###
6+
7+
### INFO
8+
# This script creates the animated illustration of blurring in episode 6
9+
###
10+
11+
### USAGE
12+
# The script requires the Python module `tqdm` which can be installed with
13+
# $ conda install tqdm
14+
#
15+
# The script can be executed with
16+
# $ python create_blur_animation.py
17+
#
18+
# The script will prompt the user to enter the kernel size.
19+
###
20+
21+
### POTENTIAL IMPROVEMENTS
22+
# - Change colors for rectangular patches in animation
23+
# - Ask for image input instead of hard-coding it
24+
# - Ask for FPS as input
25+
# - Ask for animation format output
26+
27+
# Import packages
28+
import numpy as np
29+
from scipy.ndimage import convolve
30+
from matplotlib import pyplot as plt
31+
from matplotlib import patches as p
32+
from matplotlib.animation import FuncAnimation
33+
from tqdm import tqdm
34+
35+
# Path to input and output images
36+
data_path = "../../../data/"
37+
fig_path = "../../../fig/"
38+
input_file = data_path + "letterA.tif"
39+
output_file = fig_path + "blur-demo.gif"
40+
41+
# Change here colors to improve accessibility
42+
kernel_color = "tab:red"
43+
center_color = "tab:olive"
44+
45+
### ANIMATION FUNCTIONS
46+
def init():
47+
"""
48+
Initialization function
49+
- Set image array data
50+
- Autoscale image display
51+
- Set XY coordinates of rectangular patches
52+
"""
53+
im.set_array(img_convolved)
54+
im.autoscale()
55+
k_rect.set_xy((-0.5, -0.5))
56+
c_rect1.set_xy((kernel_size / 2 - 1, kernel_size / 2 - 1))
57+
return [im, k_rect, c_rect1]
58+
59+
def update(frame):
60+
"""
61+
Animation update function. For every frame do the following:
62+
- Update X and Y coordinates of rectangular patch for kernel
63+
- Update X and Y coordinates of rectangular patch for central pixel
64+
- Update blurred image frame
65+
"""
66+
pbar.update(1)
67+
row = (frame % total_frames) // (img_pad.shape[0] - kernel_size + 1)
68+
col = (frame % total_frames) % (img_pad.shape[1] - kernel_size + 1)
69+
70+
k_rect.set_x(col - 0.5)
71+
c_rect1.set_x(col + (kernel_size/2 - 1))
72+
k_rect.set_y(row - 0.5)
73+
c_rect1.set_y(row + (kernel_size/2 - 1))
74+
75+
im.set_array(all_frames[frame])
76+
im.autoscale()
77+
78+
return [im, k_rect, c_rect1]
79+
80+
# MAIN PROGRAM
81+
if __name__ == "__main__":
82+
# simple input to ask for kernel size
83+
print("Please provide kernel size for mean filter blur animation")
84+
kernel_size = int(input("> "))
85+
86+
while kernel_size % 2 == 0:
87+
print("Please use an odd kernel size")
88+
kernel_size = int(input("> "))
89+
90+
print("Creating blurred animation with kernel size:", kernel_size)
91+
92+
# Load image
93+
img = plt.imread(input_file)
94+
95+
### HERE WE USE THE CONVOLVE FUNCTION TO GET THE FINAL BLURRED IMAGE
96+
# I chose a simple mean filter (equal kernel weights)
97+
kernel = np.ones(shape=(kernel_size, kernel_size)) / kernel_size ** 2 # create kernel
98+
# convolve the image i.e. apply mean filter
99+
img_convolved = convolve(img, kernel, mode='constant', cval=0) # pad borders with zero like below for consistency
100+
101+
102+
### HERE WE CONVOLVE MANUALLY STEP-BY-STEP TO CREATE ANIMATION
103+
img_pad = np.pad(img, (int(np.ceil(kernel_size/2) - 1), int(np.ceil(kernel_size/2) - 1))) # Pad image to deal with borders
104+
new_img = np.zeros(img.shape, dtype=np.uint16) # this will be the blurred final image
105+
106+
# add first frame with complete blurred image for print version of GIF
107+
all_frames = [img_convolved]
108+
109+
# precompute animation frames and append to the list
110+
total_frames = (img_pad.shape[0] - kernel_size + 1) * (img_pad.shape[1] - kernel_size + 1) # total frames if by change image is not squared
111+
for frame in range(total_frames):
112+
row = (frame % total_frames) // (img_pad.shape[0] - kernel_size + 1) # row index
113+
col = (frame % total_frames) % (img_pad.shape[1] - kernel_size + 1) # col index
114+
img_chunk = img_pad[row : row + kernel_size, col : col + kernel_size] # get current image chunk inside the kernel
115+
new_img[row, col] = np.mean(img_chunk).astype(np.uint16) # calculate its mean -> mean filter
116+
all_frames.append(new_img.copy()) # append to animation frames list
117+
118+
# We now have an extra frame
119+
total_frames += 1
120+
121+
### FROM HERE WE START CREATING THE ANIMATION
122+
# Initialize canvas
123+
f, (ax1, ax2) = plt.subplots(1,2, figsize=(10,5))
124+
125+
# Display the padded image -> this one won't change during the animation
126+
ax1.imshow(img_pad, cmap='gray')
127+
# Initialize the blurred image -> this is the first frame with already the final result
128+
im = ax2.imshow(img_convolved, animated=True, cmap='gray')
129+
130+
# Define rectangular patches to identify moving kernel
131+
k_rect = p.Rectangle((-0.5,-0.5), kernel_size, kernel_size, linewidth=2, edgecolor=kernel_color, facecolor='none', alpha=0.8) # kernel rectangle
132+
c_rect1 = p.Rectangle(((kernel_size/2 - 1), (kernel_size/2 - 1)), 1, 1, linewidth=2, edgecolor=center_color, facecolor='none') # central pixel rectangle
133+
# Add them to the figure
134+
ax1.add_patch(k_rect)
135+
ax1.add_patch(c_rect1)
136+
137+
# Fix limits to the right image (without padding) is the same size as the left image (with padding)
138+
ax2.set(
139+
ylim=((img_pad.shape[0] - kernel_size / 2), -kernel_size / 2),
140+
xlim=(-kernel_size / 2, (img_pad.shape[1] - kernel_size / 2))
141+
)
142+
143+
# We don't need to see the ticks
144+
ax1.axis("off")
145+
ax2.axis("off")
146+
147+
# Create progress bar to visualize animation progress
148+
pbar = tqdm(total=total_frames)
149+
150+
### HERE WE CREATE THE ANIMATION
151+
# Use FuncAnimation to create the animation
152+
ani = FuncAnimation(
153+
f, update,
154+
frames=range(total_frames),
155+
interval=50, # we could change the animation speed
156+
init_func=init,
157+
blit=True
158+
)
159+
160+
# Export animation
161+
plt.tight_layout()
162+
ani.save(output_file)
163+
pbar.close()
164+
print("Animation exported")

0 commit comments

Comments
 (0)