-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate-texture.py
executable file
·260 lines (209 loc) · 6.97 KB
/
generate-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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
#!/bin/env python
import sys
import math
from random import randint, random, choice
from enum import Enum
import PIL
from PIL import Image, ImageChops, ImageFilter, ImageEnhance
import argparse
import pathlib
# -----------------------------------------------------------------------------
class ImagePickMode(Enum):
Sequential = 'sequential'
Random = 'random'
def __str__(self):
return self.value
@staticmethod
def from_string(s):
try:
return ImagePickMode[s]
except KeyError:
raise ValueError()
# -----------------------------------------------------------------------------
# Args
parser = argparse.ArgumentParser(
prog="Texture generator",
description="Semi-random texture generator"
)
# positional arguments
# parser.add_argument("stamp_images", nargs='+', type=pathlib.Path)
parser.add_argument("stamp_image", type=pathlib.Path)
parser.add_argument("output_file", type=pathlib.Path)
# parser.add_argument(
# "--image-pick-mode",
# type=ImagePickMode.from_string,
# default=ImagePickMode.Sequential,
# choices=list(ImagePickMode)
# )
parser.add_argument("-l", "--light", action="store_true")
parser.add_argument("--no_stamp_color", action="store_true")
parser.add_argument("--no_blur", action="store_true")
parser.add_argument("--debug_color", action="store_true")
parser.add_argument(
"-m", "--min-angle",
default=-180,
type=float,
help="minimum possible angle for rotation"
);
parser.add_argument(
"-M", "--max-angle",
default=180,
type=float,
help="Maximum possible angle for rotation"
);
parser.add_argument("-x", "--width", default=2560, type=int)
parser.add_argument("-y", "--height", default=1080, type=int)
parser.add_argument(
"-d", "--density",
default=2,
type=float,
help="density as in 'how much distance between images', so d<1 is sparser and vice versa"
)
parser.add_argument(
"-s", "--stamp_scale",
default=1,
type=float,
help="scale of the stamp, in percent, as in 1==no change"
)
parser.add_argument(
"-a", "--stamp_alpha", default=0.8, type=float,
help="Base alpha that is multiplyed by the random value between min and max"
)
parser.add_argument("-o", "--opacity_min", default=0.2, type=float)
parser.add_argument("-O", "--opacity_max", default=1.0, type=float)
parser.add_argument("-b", "--blur_intensity", default=5.0, type=float)
args = parser.parse_args()
# -----------------------
# arg checking
validate = [
("opacity_min", (0.0, 1.0)),
("opacity_max", (0.0, 1.0)),
("stamp_alpha", (0.0, 1.0)),
("min_angle", (-180.0, 0.0)),
("max_angle", (0.0, 180.0)),
("stamp_scale", (0.0, 1.0)),
]
for name, (minv, maxv) in validate:
if args.__getattribute__(name) < minv:
raise argparse.ArgumentError(None, f"invalid argument {name} < {minv}")
elif args.__getattribute__(name) > maxv:
raise argparse.ArgumentError(None, f"invalid argument {name} > {maxv}")
# arg unpacking
rot_amplitude = args.max_angle - args.min_angle
rot_minimum = args.min_angle
print(f"rotation -- min: {rot_minimum} ampl: {rot_amplitude}")
opacity_min = args.opacity_min
opacity_amplitude = args.opacity_max - args.opacity_min
stamp_alpha = args.stamp_alpha
stamp_density = args.density
stamp_scale = args.stamp_scale
stamp_image = args.stamp_image
canvas_width = args.width
canvas_height = args.height
blur_intensity = args.blur_intensity
# -----------------------------------------------------------------------------
# base textures
stamp_raw = Image.open(stamp_image).convert('RGBA')
print(f"stamp raw size {stamp_raw.size}")
# split alpha and multiply it by value
r, g, b, a = stamp_raw.split()
a = a.point(lambda i: i * stamp_alpha)
stamp_raw = Image.merge(
'RGBA',
(r, g, b, a) if not args.no_stamp_color else (a, a, a, a)
)
#make a square with max(dim) * sqrt 2 side so we can rotate the image freely
max_side = int(max(stamp_raw.size) * math.sqrt(2.0))
print(f"stamp largest side: {max_side}");
stamp = Image.new("RGBA", (max_side, max_side), color=(
255, 0, 0, 0 if not args.debug_color else 20
))
stamp.paste(stamp_raw, (
int(stamp.size[0]/2 - stamp_raw.size[0]/2),
int(stamp.size[1]/2 - stamp_raw.size[1]/2)
))
# -----------------------------------------------------------------------------
# canvas
base_color = 255 if args.light else 0
canvas = Image.new(
"RGBA",
(args.width, args.height),
(base_color, base_color, base_color, 255)
)
# -----------------------------------------------------------------------------
# Loop parameters
# stamp scale is applied here because otherwise the rotation result doesn't
# looks good
stamp_w = stamp_raw.size[0] * stamp_scale
stamp_h = stamp_raw.size[1] * stamp_scale
# maximum width and height offset
x_ofs_max = int((stamp_w / 2) * 0.5)
y_ofs_max = int((stamp_h / 2) * 0.5)
x_step = int(stamp_w / args.density)
y_step = int(stamp_h / args.density)
print(f"image size: {stamp.size} mode: {stamp.mode}")
print(f"canvas size: {canvas.size} mode {canvas.mode}")
print(f"step: {(x_step, y_step)}");
# -----------------------------------------------------------------------------
# generate positions [vert, horiz, rotation, scale]
ofs = -5
from itertools import chain, repeat
opacities = [
op for op in chain(
repeat(0.1, 30),
repeat(0.2, 30),
repeat(0.4, 20),
repeat(0.8, 5),
repeat(1.0, 5)
)
# 0.1 + (x / 90.0) * 0.5
# if x < 90 else
# x/100.0
# for x in range(0, 100)
# (math.exp(x/100 + ofs)/(1 + math.exp(x/100 + ofs)))
# for x in range(0, 1000)
]
stamp_positions = [
[
x + randint(-y_ofs_max, y_ofs_max), # xpos
y + randint(-x_ofs_max, x_ofs_max), # ypos
random() * rot_amplitude + rot_minimum, #rotation
choice(opacities),
# opacity_min + opacity_amplitude * random(), # opacity
stamp
]
for x in range(0, args.width, x_step)
for y in range(0, args.height, y_step)
]
from operator import itemgetter
stamp_positions.sort(key=lambda k: k[3])
max_index = float(len(stamp_positions))
# textues_len = len(textures)
# -----------------------------------------------------------------------------
# Bake final image
for index, (x_pos, y_pos, rotation, opacity, stamp) in enumerate(stamp_positions):
sys.stdout.write(f"\r{100.0 * index / max_index:2.1f} %")
sys.stdout.flush()
r, g, b, a = stamp.split()
color = a.point(lambda i: i * opacity)
a = a.point(lambda i: i * 0.95)
new_stamp = Image.merge(
'RGBA', (color, color, color, a) if args.no_stamp_color else (r, g, b, a)
)\
.rotate(rotation)\
.resize((
int(stamp.size[0] * stamp_scale),
int(stamp.size[1] * stamp_scale)
))
# .filter(ImageFilter.GaussianBlur(blur_intensity * (1.0 - opacity)))
# TODO: add back blur
canvas.alpha_composite(
new_stamp,
(
x_pos - int(new_stamp.size[0]/2),
y_pos - int(new_stamp.size[1]/2)
)
)
# Save result
canvas.save(args.output_file)
print("\nDone!")