Skip to content

Instantly share code, notes, and snippets.

@neale
Created August 7, 2022 20:26
Show Gist options
  • Save neale/474bcc55521c8d6b0dc94d428137b409 to your computer and use it in GitHub Desktop.
Save neale/474bcc55521c8d6b0dc94d428137b409 to your computer and use it in GitHub Desktop.
Perlin noise image augmentation
import sys
import numpy as np
import cv2
from perlin_noise import PerlinNoise
import glob
def vector_field(x, y, noise, scale=0.01, w=100):
noise_x = w * noise([scale*x, scale*y])
noise_y = w * noise([100+scale*x, scale*y])
return noise_x, noise_y
if __name__ == '__main__':
w = 400
scale = 0.008
print (len(glob.glob('*.png')), 'images') ## change to refect path
for img_path in glob.glob('*.png'):
for n in range(1, 5):
for w in [300, 400, 500, 600]:
noise = PerlinNoise(n)
print ('reading', img_path, 'w:', w, 'n:', n)
x = cv2.imread(img_path)
x = x / 255.
result2d = np.empty_like(x)
for i in range(x.shape[0]):
for j in range(x.shape[1]):
new_i, new_j = vector_field(i, j, noise, scale, w)
out_x = int(np.clip(np.floor(i+new_i), 0, x.shape[0]-1))
out_y = int(np.clip(np.floor(j+new_j), 0, x.shape[1]-1))
result2d[out_x, out_y] = x[i, j]
print (result2d.min(), result2d.max())
result2d[result2d == 0.] = 1.0
result2d = (result2d*255.).astype(np.uint8)
cv2.imwrite(f'{img_path.split(".")[0]}n{n}w{w}.png', result2d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment