forked from z0xi/n2n-watermark-remove
-
Notifications
You must be signed in to change notification settings - Fork 0
/
noise_model_test.py
94 lines (74 loc) · 3 KB
/
noise_model_test.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import argparse
import string
import random
import numpy as np
import cv2
from PIL import Image
def get_noise_model(noise_type="gaussian,0,50"):
tokens = noise_type.split(sep=",")
if tokens[0] == "gaussian":
min_stddev = int(tokens[1])
max_stddev = int(tokens[2])
def gaussian_noise(img):
noise_img = img.astype(np.float)
stddev = np.random.uniform(min_stddev, max_stddev)
noise = np.random.randn(*img.shape) * stddev
noise_img += noise
noise_img = np.clip(noise_img, 0, 255).astype(np.uint8)
return noise_img
return gaussian_noise
elif tokens[0] == "clean":
return lambda img: img
elif tokens[0] == "text":
min_occupancy = int(tokens[1])
max_occupancy = int(tokens[2])
def add_text(img):
img = img.copy()
TRANSPARENCY = random.randint(88, 97)
image = Image.fromarray(img)
watermark = Image.open('./1.png')
if watermark.mode!='RGBA':
alpha = Image.new('L', watermark.size, 255)
watermark.putalpha(alpha)
random_W = random.randint(-750 , 45)
random_H = random.randint(-500 , 30)
paste_mask = watermark.split()[3].point(lambda i: i * TRANSPARENCY / 100.)
image.paste(watermark, (random_W , random_H ), mask=paste_mask)
return img #测试时请注释这一行 启用48行
# return image #训练模型时请注释这一行 启用47行
return add_text
elif tokens[0] == "impulse":
min_occupancy = int(tokens[1])
max_occupancy = int(tokens[2])
def add_impulse_noise(img):
occupancy = np.random.uniform(min_occupancy, max_occupancy)
mask = np.random.binomial(size=img.shape, n=1, p=occupancy / 100)
noise = np.random.randint(256, size=img.shape)
img = img * (1 - mask) + noise * mask
return img.astype(np.uint8)
return add_impulse_noise
else:
raise ValueError("noise_type should be 'gaussian', 'clean', 'text', or 'impulse'")
def get_args():
parser = argparse.ArgumentParser(description="test noise model",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--image_size", type=int, default=256,
help="training patch size")
parser.add_argument("--noise_model", type=str, default="gaussian,0,50",
help="noise model to be tested")
args = parser.parse_args()
return args
def main():
args = get_args()
image_size = args.image_size
noise_model = get_noise_model(args.noise_model)
while True:
image = np.ones((image_size, image_size, 3), dtype=np.uint8) * 128
noisy_image = noise_model(image)
cv2.imshow("noise image", noisy_image)
key = cv2.waitKey(-1)
# "q": quit
if key == 113:
return 0
if __name__ == '__main__':
main()