Skip to content

Instantly share code, notes, and snippets.

@napsternxg
Last active July 7, 2023 08:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save napsternxg/5862f216e4011541f805 to your computer and use it in GitHub Desktop.
Save napsternxg/5862f216e4011541f805 to your computer and use it in GitHub Desktop.
Random Walk Image Generation
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
"""
Random Walk Image Generator
@Author: Shubhanshu Mishra
@Website: http://shubhanshu.com
@LICENSE: MIT
"""
# coding: utf-8
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
# In[2]:
def get_color(colors=None, color_channels=3):
if colors is None:
return np.random.rand(color_channels)
else:
return colors[np.random.randint(len(colors))]
def gen_image(n = 200, walks = 5, fig_dim = 10, density = 0.5, bg_grey = 1, color_change_steps=50,\
colors_rgb = True, colors = None, filename=None, verbose=False):
color_channels = 3
if not colors_rgb:
color_channels = 1
figsize = (fig_dim, )*2
img = np.ones((n,n,3)) * bg_grey
mat = np.zeros((n,n))
for i in xrange(walks):
init_x, init_y = np.random.randint(0,2, size=(2))
color = get_color(colors=colors, color_channels=color_channels)
img[init_x, init_y] = color
mat[init_x, init_y] = 1
num_steps = np.random.randint(int(n*n*density))
num_steps = int(np.random.rand()*n*n*density)
next_x, next_y = init_x, init_y
change_steps = 0
for j in xrange(num_steps):
nudge = np.random.randint(-1,2, size=2)
next_x, next_y = (next_x + nudge[0]) % n, (next_y + nudge[1]) % n
if mat[next_x, next_y] == 1 or change_steps >= color_change_steps:
color = get_color(colors=colors, color_channels=color_channels)
change_steps = 0
change_steps += 1
img[next_x, next_y] = color
if verbose:
print "Walk %s with %s steps" % (i, num_steps)
plt.clf()
plt.figure(figsize=figsize)
plt.imshow(img)
plt.axis('off')
if filename is not None:
plt.savefig(filename)
else:
plt.show()
# In[3]:
# In[ ]:
if __name__ == "__main__":
base_file = "rand_img_%s.png"
num_images = 500
for i in xrange(num_images):
gen_image(filename=base_file % i)
print "Finished generating %s images" % (i + 1)
# In[ ]:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment