Debian Codegraph @

demo/image_blender.py

raw symbols SCIP
1 #!/usr/bin/env python
2
3 # Copyright (c) 2006-2012 Filip Wasilewski <http://en.ig.ma/>
4 # Copyright (c) 2012-2016 The PyWavelets Developers
5 # <https://github.com/PyWavelets/pywt>
6 # See COPYING for license details.
7
8 """
9 Wavelet Image Blender.
10
11 Blend image A with texture extracted from image B by selecting
12 detail coefficients:
13
14 ----------------- -----------------
15 | | | |
16 | | | |
17 | | | |
18 | A | | B |
19 | | | |
20 | | | |
21 | | | |
22 ----------------- -----------------
23
24 | |
25 2D DWT | 2D DWT |
26 V V
27
28 ----------------- --------- -----------------
29 | | | | | | |
30 | A(LL) | H(LH) | | H(LH) | | |
31 | | | | | IDWT | |
32 ----------------- + ----------------- -----> | C |
33 | | | | | | | |
34 | V(HL) | D(HH) | | V(HL) | D(HH) | | |
35 | | | | | | | |
36 ----------------- ----------------- -----------------
37 (details only)
38 """
39
40 import optparse
41 import os
42 import sys
43 if os.name == 'nt':
44 from time import clock # noqa
45 else:
46 from time import time as clock # noqa
47
48 from PIL import Image # PIL
49 import numpy # http://www.scipy.org
50
51 import pywt
52
53
54 def image2array(image):
55 """PIL Image to NumPy array"""
56 assert image.mode in ('L', 'RGB', 'CMYK')
57 arr = numpy.fromstring(image.tobytes(), numpy.uint8)
58 arr.shape = (image.size[1], image.size[0], len(image.getbands()))
59 return arr.swapaxes(0, 2).swapaxes(1, 2).astype(numpy.float32)
60
61
62 def array2image(arr, mode):
63 """NumPy array to PIL Image"""
64 arr = arr.swapaxes(1, 2).swapaxes(0, 2)
65 arr[arr < 0] = 0
66 arr[arr > 255] = 255
67 arr = numpy.fix(arr).astype(numpy.uint8)
68 return Image.frombytes(mode, arr.shape[1::-1], arr.tobytes())
69
70
71 def load_image(path, mode=None, size=None):
72 """Load image"""
73 im = Image.open(path)
74
75 if im.mode not in ('L', 'P', 'RGB', 'CMYK'):
76 raise TypeError("Image mode must be 'L', 'P', 'RGB' or 'CMYK'")
77
78 if mode is not None:
79 if mode == 'P':
80 raise ValueError("Mode must be 'L', 'RGB' or 'CMYK'")
81 im = im.convert(mode)
82 elif im.mode == 'P':
83 im = im.convert('RGB')
84
85 if size is not None and im.size != size:
86 im = im.resize(size, Image.ANTIALIAS)
87 return im
88
89
90 def blend_images(base, texture, wavelet, level, mode='smooth', base_gain=None,
91 texture_gain=None):
92 """Blend loaded images at `level` of granularity using `wavelet`"""
93
94 base_data = image2array(base)
95 texture_data = image2array(texture)
96 output_data = []
97
98 # process color bands
99 for base_band, texture_band in zip(base_data, texture_data):
100 # multilevel dwt
101 base_band_coeffs = pywt.wavedec2(base_band, wavelet, mode, level)
102 texture_band_coeffs = pywt.wavedec2(texture_band, wavelet, mode, level)
103
104 # average coefficients of base image
105 output_band_coeffs = [base_band_coeffs[0]] # cA
106 del base_band_coeffs[0], texture_band_coeffs[0]
107
108 # blend details coefficients
109 for n, (base_band_details, texture_band_details) in enumerate(
110 zip(base_band_coeffs, texture_band_coeffs)):
111 blended_details = []
112 for (base_detail, texture_detail) in zip(base_band_details,
113 texture_band_details):
114 if base_gain is not None:
115 base_detail *= base_gain
116 if texture_gain is not None:
117 texture_detail *= texture_gain
118
119 # select coeffs with greater energy
120 blended = numpy.where(abs(base_detail) > abs(texture_detail),
121 base_detail, texture_detail)
122 blended_details.append(blended)
123
124 base_band_coeffs[n] = texture_band_coeffs[n] = None
125 output_band_coeffs.append(blended_details)
126
127 # multilevel idwt
128 new_band = pywt.waverec2(output_band_coeffs, wavelet, mode)
129 output_data.append(new_band)
130 del new_band, base_band_coeffs, texture_band_coeffs
131
132 del base_data, texture_data
133 output_data = numpy.array(output_data)
134
135 return array2image(output_data, base.mode)
136
137
138 def main():
139 usage = "usage: %prog -b BASE -t TEXTURE -o OUTPUT "\
140 "[-w WAVELET] [-l LEVEL] [-m MODE]"
141 parser = optparse.OptionParser(usage=usage)
142 parser.add_option("-b", "--base", dest="base", metavar="BASE",
143 help="base image name")
144 parser.add_option("-t", "--texture", dest="texture", metavar="TEXTURE",
145 help="texture image name")
146 parser.add_option("-o", "--output", dest="output", metavar="OUTPUT",
147 help="output image name")
148 parser.add_option("-w", "--wavelet", dest="wavelet", metavar="WAVELET",
149 default='db2', help="wavelet name [default: %default]")
150 parser.add_option("-l", "--level", dest="level", metavar="LEVEL",
151 type="int", default=4,
152 help="decomposition level [default: %default]")
153 parser.add_option("-m", "--mode", dest="mode", metavar="MODE",
154 default='symmetric',
155 help="decomposition mode. Adjust this if"
156 " getting edge artifacts [default: %default]")
157 parser.add_option("-x", "--base_gain", dest="base_gain", metavar="BG",
158 type="float", default=None,
159 help="Base image gain [default: %default]")
160 parser.add_option("-y", "--texture_gain", dest="texture_gain",
161 metavar="TG", type="float", default=None,
162 help="Texture image gain [default: %default]")
163 parser.add_option("--timeit", dest="timeit", action="store_true",
164 default=False, help="time blending operations")
165
166 (options, args) = parser.parse_args()
167
168 if None in (options.base, options.texture, options.output):
169 parser.print_help()
170 sys.exit(-1)
171
172 base = load_image(options.base)
173 texture = load_image(options.texture, base.mode, base.size)
174
175 if options.timeit:
176 t = clock()
177
178 im = blend_images(base, texture, options.wavelet, options.level,
179 options.mode, options.base_gain, options.texture_gain)
180
181 if options.timeit:
182 print("%.3fs" % (clock() - t))
183
184 im.save(options.output)
185
186 if __name__ == '__main__':
187 main()