-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnoise_texture.py
68 lines (55 loc) · 2.15 KB
/
noise_texture.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import numpy as np
import cv2
BG_COLOR = 209
BG_SIGMA = 5
MONOCHROME = 1
def blank_image(width=1024, height=1024, background=BG_COLOR):
"""
It creates a blank image of the given background color
"""
img = np.full((height, width, MONOCHROME), background, np.uint8)
return img
def add_noise(img, sigma=BG_SIGMA):
"""
Adds noise to the existing image
"""
width, height, ch = img.shape
n = noise(width, height, sigma=sigma)
img = img + n
return img.clip(0, 255)
def noise(width, height, ratio=1, sigma=BG_SIGMA):
"""
The function generates an image, filled with gaussian nose. If ratio parameter is specified,
noise will be generated for a lesser image and then it will be upscaled to the original size.
In that case noise will generate larger square patterns. To avoid multiple lines, the upscale
uses interpolation.
:param ratio: the size of generated noise "pixels"
:param sigma: defines bounds of noise fluctuations
"""
mean = 0
assert width % ratio == 0, "Can't scale image with of size {} and ratio {}".format(
width, ratio)
assert height % ratio == 0, "Can't scale image with of size {} and ratio {}".format(
height, ratio)
h = int(height / ratio)
w = int(width / ratio)
result = np.random.normal(mean, sigma, (w, h, MONOCHROME))
if ratio > 1:
result = cv2.resize(result, dsize=(width, height),
interpolation=cv2.INTER_LINEAR)
return result.reshape((width, height, MONOCHROME))
def texture(image, sigma=BG_SIGMA, turbulence=2):
"""
Consequently applies noise patterns to the original image from big to small.
sigma: defines bounds of noise fluctuations
turbulence: defines how quickly big patterns will be replaced with the small ones. The lower
value - the more iterations will be performed during texture generation.
"""
result = image.astype(float)
cols, rows, ch = image.shape
ratio = cols
while not ratio == 1:
result += noise(cols, rows, ratio, sigma=sigma)
ratio = (ratio // turbulence) or 1
cut = np.clip(result, 0, 255)
return cut.astype(np.uint8)