Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 474 lines (387 sloc) 13.656 kb
9470925 @rgommers DOC: merge wiki edits for misc module.
rgommers authored
1 """
2 A collection of image utilities using the Python Imaging Library (PIL).
3
4 Note that PIL is not a dependency of SciPy and this module is not
5 available on systems that don't have PIL installed.
6
7 """
5f4c579 @pv MAINT: add relevant from __future__ import to all files
pv authored
8 from __future__ import division, print_function, absolute_import
9
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
10 # Functions which need the PIL
11
24c0041 @timleslie remove unused imports and alias of Numeric -> numpy
timleslie authored
12 import numpy
e441986 @stefanv Clean up misc.pilutil.imshow.
stefanv authored
13 import tempfile
b71bc89 @pearu 1) Finished applying ppimport hooks to scipy.
pearu authored
14
24c0041 @timleslie remove unused imports and alias of Numeric -> numpy
timleslie authored
15 from numpy import amin, amax, ravel, asarray, cast, arange, \
6d3bfdc @stefanv Fix imresize, add test.
stefanv authored
16 ones, newaxis, transpose, mgrid, iscomplexobj, sum, zeros, uint8, \
17 issubdtype, array
b71bc89 @pearu 1) Finished applying ppimport hooks to scipy.
pearu authored
18
19fea6d @cgohlke BUG: fix several small bugs in rbf, io.harwell_boeing and misc.
cgohlke authored
19 try:
20 from PIL import Image, ImageFilter
21 except ImportError:
22 import Image
23 import ImageFilter
24
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
25
5549cde Added radon transform and bug fixes.
Travis Oliphant authored
26 __all__ = ['fromimage','toimage','imsave','imread','bytescale',
b71bc89 @pearu 1) Finished applying ppimport hooks to scipy.
pearu authored
27 'imrotate','imresize','imshow','imfilter','radon']
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
28
19fea6d @cgohlke BUG: fix several small bugs in rbf, io.harwell_boeing and misc.
cgohlke authored
29
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
30 # Returns a byte-scaled image
31 def bytescale(data, cmin=None, cmax=None, high=255, low=0):
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
32 """
9470925 @rgommers DOC: merge wiki edits for misc module.
rgommers authored
33 Byte scales an array (image).
34
1aee114 @rgommers BUG: fix pilutil.bytescale scaling behavior. Closes #1748.
rgommers authored
35 Byte scaling means converting the input image to uint8 dtype and scaling
36 the range to ``(low, high)`` (default 0-255).
37 If the input image already has dtype uint8, no scaling is done.
38
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
39 Parameters
40 ----------
9470925 @rgommers DOC: merge wiki edits for misc module.
rgommers authored
41 data : ndarray
42 PIL image data array.
1aee114 @rgommers BUG: fix pilutil.bytescale scaling behavior. Closes #1748.
rgommers authored
43 cmin : scalar, optional
44 Bias scaling of small values. Default is ``data.min()``.
45 cmax : scalar, optional
46 Bias scaling of large values. Default is ``data.max()``.
47 high : scalar, optional
48 Scale max value to `high`. Default is 255.
49 low : scalar, optional
50 Scale min value to `low`. Default is 0.
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
51
52 Returns
53 -------
1aee114 @rgommers BUG: fix pilutil.bytescale scaling behavior. Closes #1748.
rgommers authored
54 img_array : uint8 ndarray
55 The byte-scaled array.
9470925 @rgommers DOC: merge wiki edits for misc module.
rgommers authored
56
57 Examples
58 --------
59 >>> img = array([[ 91.06794177, 3.39058326, 84.4221549 ],
60 [ 73.88003259, 80.91433048, 4.88878881],
61 [ 51.53875334, 34.45808177, 27.5873488 ]])
62 >>> bytescale(img)
63 array([[255, 0, 236],
64 [205, 225, 4],
65 [140, 90, 70]], dtype=uint8)
66 >>> bytescale(img, high=200, low=100)
67 array([[200, 100, 192],
68 [180, 188, 102],
69 [155, 135, 128]], dtype=uint8)
70 >>> bytescale(img, cmin=0, cmax=255)
71 array([[91, 3, 84],
72 [74, 81, 5],
73 [52, 34, 28]], dtype=uint8)
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
74
75 """
0b9aefb @stefanv Fix dtype comparison.
stefanv authored
76 if data.dtype == uint8:
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
77 return data
1aee114 @rgommers BUG: fix pilutil.bytescale scaling behavior. Closes #1748.
rgommers authored
78
79 if high < low:
80 raise ValueError("`high` should be larger than `low`.")
81
82 if cmin is None:
83 cmin = data.min()
84 if cmax is None:
85 cmax = data.max()
86
87 cscale = cmax - cmin
88 if cscale < 0:
89 raise ValueError("`cmax` should be larger than `cmin`.")
90 elif cscale == 0:
91 cscale = 1
92
93 scale = float(high - low) / cscale
94 bytedata = (data * 1.0 - cmin) * scale + 0.4999
95 bytedata[bytedata > high] = high
96 bytedata[bytedata < 0] = 0
97 return cast[uint8](bytedata) + cast[uint8](low)
ebea7bf Run reindent.py (script distributed with Python) over the source to r…
cookedm authored
98
471f247 Changes so that array conversion happens correctly. Fixed speed of f…
Travis Oliphant authored
99 def imread(name,flatten=0):
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
100 """
101 Read an image file from a filename.
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
102
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
103 Parameters
104 ----------
105 name : str
106 The file name to be read.
107 flatten : bool, optional
108 If True, flattens the color layers into a single gray-scale layer.
109
110 Returns
111 -------
b853c34 @rgommers DOC: merge doc wiki edits. Thanks to everyone who contributed.
rgommers authored
112 imread : ndarray
113 The array obtained by reading image from file `name`.
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
114
115 Notes
116 -----
117 The image is flattened by calling convert('F') on
118 the resulting image object.
471f247 Changes so that array conversion happens correctly. Fixed speed of f…
Travis Oliphant authored
119
7b5f7fe Added resize and filter to pilutil.py
Travis Oliphant authored
120 """
471f247 Changes so that array conversion happens correctly. Fixed speed of f…
Travis Oliphant authored
121
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
122 im = Image.open(name)
471f247 Changes so that array conversion happens correctly. Fixed speed of f…
Travis Oliphant authored
123 return fromimage(im,flatten=flatten)
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
124
125 def imsave(name, arr):
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
126 """
b853c34 @rgommers DOC: merge doc wiki edits. Thanks to everyone who contributed.
rgommers authored
127 Save an array as an image.
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
128
129 Parameters
130 ----------
05b26a5 @rgommers DOC: merge wiki edits, lib, io, misc modules and main docstring.
rgommers authored
131 name : str
b853c34 @rgommers DOC: merge doc wiki edits. Thanks to everyone who contributed.
rgommers authored
132 Output filename.
05b26a5 @rgommers DOC: merge wiki edits, lib, io, misc modules and main docstring.
rgommers authored
133 arr : ndarray, MxN or MxNx3 or MxNx4
b853c34 @rgommers DOC: merge doc wiki edits. Thanks to everyone who contributed.
rgommers authored
134 Array containing image values. If the shape is ``MxN``, the array
135 represents a grey-level image. Shape ``MxNx3`` stores the red, green
136 and blue bands along the last dimension. An alpha layer may be
137 included, specified as the last colour band of an ``MxNx4`` array.
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
138
b853c34 @rgommers DOC: merge doc wiki edits. Thanks to everyone who contributed.
rgommers authored
139 Examples
140 --------
141 Construct an array of gradient intensity values and save to file:
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
142
b853c34 @rgommers DOC: merge doc wiki edits. Thanks to everyone who contributed.
rgommers authored
143 >>> x = np.zeros((255, 255))
144 >>> x = np.zeros((255, 255), dtype=np.uint8)
145 >>> x[:] = np.arange(255)
146 >>> imsave('/tmp/gradient.png', x)
147
148 Construct an array with three colour bands (R, G, B) and store to file:
149
150 >>> rgb = np.zeros((255, 255, 3), dtype=np.uint8)
151 >>> rgb[..., 0] = np.arange(255)
152 >>> rgb[..., 1] = 55
153 >>> rgb[..., 2] = 1 - np.arange(255)
154 >>> imsave('/tmp/rgb_gradient.png', rgb)
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
155
7b5f7fe Added resize and filter to pilutil.py
Travis Oliphant authored
156 """
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
157 im = toimage(arr)
158 im.save(name)
159 return
160
471f247 Changes so that array conversion happens correctly. Fixed speed of f…
Travis Oliphant authored
161 def fromimage(im, flatten=0):
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
162 """
163 Return a copy of a PIL image as a numpy array.
164
165 Parameters
166 ----------
167 im : PIL image
168 Input image.
169 flatten : bool
170 If true, convert the output to grey-scale.
171
172 Returns
173 -------
b853c34 @rgommers DOC: merge doc wiki edits. Thanks to everyone who contributed.
rgommers authored
174 fromimage : ndarray
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
175 The different colour bands/channels are stored in the
176 third dimension, such that a grey-image is MxN, an
177 RGB-image MxNx3 and an RGBA-image MxNx4.
471f247 Changes so that array conversion happens correctly. Fixed speed of f…
Travis Oliphant authored
178
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
179 """
5e85e5c @stefanv Fix fromimage for monochrome images (closes ticket #259). Add tests.
stefanv authored
180 if not Image.isImageType(im):
181 raise TypeError("Input is not a PIL image.")
471f247 Changes so that array conversion happens correctly. Fixed speed of f…
Travis Oliphant authored
182 if flatten:
183 im = im.convert('F')
14c8142 @rgommers BUG: workaround for misc.imread crash for 1-bit images. Closes #1613.
rgommers authored
184 elif im.mode == '1':
185 # workaround for crash in PIL, see #1613.
186 im.convert('L')
187
5e85e5c @stefanv Fix fromimage for monochrome images (closes ticket #259). Add tests.
stefanv authored
188 return array(im)
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
189
190 _errstr = "Mode is unknown or incompatible with input array shape."
c2bb0e7 ENH: misc: Don't use plain assert for argument validation.
warren.weckesser authored
191
192 def toimage(arr, high=255, low=0, cmin=None, cmax=None, pal=None,
193 mode=None, channel_axis=None):
0d06383 @rgommers DOC: fix more Sphinx issues.
rgommers authored
194 """Takes a numpy array and returns a PIL image.
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
195
0d06383 @rgommers DOC: fix more Sphinx issues.
rgommers authored
196 The mode of the PIL image depends on the array shape and the `pal` and
197 `mode` keywords.
198
199 For 2-D arrays, if `pal` is a valid (N,3) byte-array giving the RGB values
200 (from 0 to 255) then ``mode='P'``, otherwise ``mode='L'``, unless mode
201 is given as 'F' or 'I' in which case a float and/or integer array is made.
202
203 Notes
204 -----
205 For 3-D arrays, the `channel_axis` argument tells which dimension of the
206 array holds the channel data.
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
207
208 For 3-D arrays if one of the dimensions is 3, the mode is 'RGB'
0d06383 @rgommers DOC: fix more Sphinx issues.
rgommers authored
209 by default or 'YCbCr' if selected.
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
210
24c0041 @timleslie remove unused imports and alias of Numeric -> numpy
timleslie authored
211 The numpy array must be either 2 dimensional or 3 dimensional.
0d06383 @rgommers DOC: fix more Sphinx issues.
rgommers authored
212
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
213 """
9383511 @pearu Using faster implementation of Numeric.asarray. Clean ups and importi…
pearu authored
214 data = asarray(arr)
4d3ec69 Fixed toimage bug with complex array inputs.
Travis Oliphant authored
215 if iscomplexobj(data):
e2ed1e0 ENH: misc: update 'raise' statements
warren.weckesser authored
216 raise ValueError("Cannot convert a complex-valued array.")
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
217 shape = list(data.shape)
218 valid = len(shape)==2 or ((len(shape)==3) and \
219 ((3 in shape) or (4 in shape)))
c2bb0e7 ENH: misc: Don't use plain assert for argument validation.
warren.weckesser authored
220 if not valid:
221 raise ValueError("'arr' does not have a suitable array shape for any mode.")
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
222 if len(shape) == 2:
223 shape = (shape[1],shape[0]) # columns show up first
42178e2 Fixed toimage to not scale floating point arrays if mode is F. Added…
Travis Oliphant authored
224 if mode == 'F':
bfded84 misc/: convert from typecodes to dtypes
cookedm authored
225 data32 = data.astype(numpy.float32)
226 image = Image.fromstring(mode,shape,data32.tostring())
42178e2 Fixed toimage to not scale floating point arrays if mode is F. Added…
Travis Oliphant authored
227 return image
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
228 if mode in [None, 'L', 'P']:
229 bytedata = bytescale(data,high=high,low=low,cmin=cmin,cmax=cmax)
230 image = Image.fromstring('L',shape,bytedata.tostring())
231 if pal is not None:
bfded84 misc/: convert from typecodes to dtypes
cookedm authored
232 image.putpalette(asarray(pal,dtype=uint8).tostring())
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
233 # Becomes a mode='P' automagically.
234 elif mode == 'P': # default gray-scale
bfded84 misc/: convert from typecodes to dtypes
cookedm authored
235 pal = arange(0,256,1,dtype=uint8)[:,newaxis] * \
236 ones((3,),dtype=uint8)[newaxis,:]
237 image.putpalette(asarray(pal,dtype=uint8).tostring())
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
238 return image
239 if mode == '1': # high input gives threshold for 1
a785a7f Fix use of 'b' in pilutil
Travis Oliphant authored
240 bytedata = (data > high)
ebea7bf Run reindent.py (script distributed with Python) over the source to r…
cookedm authored
241 image = Image.fromstring('1',shape,bytedata.tostring())
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
242 return image
243 if cmin is None:
244 cmin = amin(ravel(data))
245 if cmax is None:
246 cmax = amax(ravel(data))
247 data = (data*1.0 - cmin)*(high-low)/(cmax-cmin) + low
42178e2 Fixed toimage to not scale floating point arrays if mode is F. Added…
Travis Oliphant authored
248 if mode == 'I':
bfded84 misc/: convert from typecodes to dtypes
cookedm authored
249 data32 = data.astype(numpy.uint32)
250 image = Image.fromstring(mode,shape,data32.tostring())
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
251 else:
e2ed1e0 ENH: misc: update 'raise' statements
warren.weckesser authored
252 raise ValueError(_errstr)
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
253 return image
254
255 # if here then 3-d array with a 3 or a 4 in the shape length.
256 # Check for 3 in datacube shape --- 'RGB' or 'YCbCr'
257 if channel_axis is None:
258 if (3 in shape):
1e1389b Make use of flatnonzero
Travis Oliphant authored
259 ca = numpy.flatnonzero(asarray(shape) == 3)[0]
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
260 else:
1e1389b Make use of flatnonzero
Travis Oliphant authored
261 ca = numpy.flatnonzero(asarray(shape) == 4)
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
262 if len(ca):
263 ca = ca[0]
264 else:
e2ed1e0 ENH: misc: update 'raise' statements
warren.weckesser authored
265 raise ValueError("Could not find channel dimension.")
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
266 else:
267 ca = channel_axis
268
2fa139b Fixed code for color images.
Travis Oliphant authored
269 numch = shape[ca]
270 if numch not in [3,4]:
e2ed1e0 ENH: misc: update 'raise' statements
warren.weckesser authored
271 raise ValueError("Channel axis dimension is not valid.")
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
272
273 bytedata = bytescale(data,high=high,low=low,cmin=cmin,cmax=cmax)
2fa139b Fixed code for color images.
Travis Oliphant authored
274 if ca == 2:
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
275 strdata = bytedata.tostring()
2fa139b Fixed code for color images.
Travis Oliphant authored
276 shape = (shape[1],shape[0])
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
277 elif ca == 1:
2fa139b Fixed code for color images.
Travis Oliphant authored
278 strdata = transpose(bytedata,(0,2,1)).tostring()
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
279 shape = (shape[2],shape[0])
2fa139b Fixed code for color images.
Travis Oliphant authored
280 elif ca == 0:
281 strdata = transpose(bytedata,(1,2,0)).tostring()
282 shape = (shape[2],shape[1])
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
283 if mode is None:
284 if numch == 3: mode = 'RGB'
285 else: mode = 'RGBA'
286
287
288 if mode not in ['RGB','RGBA','YCbCr','CMYK']:
e2ed1e0 ENH: misc: update 'raise' statements
warren.weckesser authored
289 raise ValueError(_errstr)
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
290
291 if mode in ['RGB', 'YCbCr']:
c2bb0e7 ENH: misc: Don't use plain assert for argument validation.
warren.weckesser authored
292 if numch != 3:
293 raise ValueError("Invalid array shape for mode.")
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
294 if mode in ['RGBA', 'CMYK']:
c2bb0e7 ENH: misc: Don't use plain assert for argument validation.
warren.weckesser authored
295 if numch != 4:
296 raise ValueError("Invalid array shape for mode.")
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
297
c2bb0e7 ENH: misc: Don't use plain assert for argument validation.
warren.weckesser authored
298 # Here we know data and mode is correct
d135e5e Moved PIL utility functions into their own file.
Travis Oliphant authored
299 image = Image.fromstring(mode, shape, strdata)
300 return image
301
39d3923 Bug fixes.
Travis Oliphant authored
302 def imrotate(arr,angle,interp='bilinear'):
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
303 """
304 Rotate an image counter-clockwise by angle degrees.
305
306 Parameters
307 ----------
05b26a5 @rgommers DOC: merge wiki edits, lib, io, misc modules and main docstring.
rgommers authored
308 arr : ndarray
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
309 Input array of image to be rotated.
310 angle : float
311 The angle of rotation.
312 interp : str, optional
313 Interpolation
314
05b26a5 @rgommers DOC: merge wiki edits, lib, io, misc modules and main docstring.
rgommers authored
315 - 'nearest' : for nearest neighbor
316 - 'bilinear' : for bilinear
317 - 'cubic' : cubic
318 - 'bicubic' : for bicubic
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
319
320 Returns
321 -------
05b26a5 @rgommers DOC: merge wiki edits, lib, io, misc modules and main docstring.
rgommers authored
322 imrotate : ndarray
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
323 The rotated array of image.
324
7b5f7fe Added resize and filter to pilutil.py
Travis Oliphant authored
325 """
326 arr = asarray(arr)
327 func = {'nearest':0,'bilinear':2,'bicubic':3,'cubic':3}
328 im = toimage(arr)
5549cde Added radon transform and bug fixes.
Travis Oliphant authored
329 im = im.rotate(angle,resample=func[interp])
39d3923 Bug fixes.
Travis Oliphant authored
330 return fromimage(im)
7b5f7fe Added resize and filter to pilutil.py
Travis Oliphant authored
331
332 def imshow(arr):
9470925 @rgommers DOC: merge wiki edits for misc module.
rgommers authored
333 """
334 Simple showing of an image through an external viewer.
335
336 Uses the image viewer specified by the environment variable
337 SCIPY_PIL_IMAGE_VIEWER, or if that is not defined then `see`,
338 to view a temporary file generated from array data.
339
340 Parameters
341 ----------
342 arr : ndarray
343 Array of image data to show.
344
345 Returns
346 -------
347 None
348
349 Examples
350 --------
351 >>> a = np.tile(np.arange(255), (255,1))
352 >>> from scipy import misc
353 >>> misc.pilutil.imshow(a)
354
7b5f7fe Added resize and filter to pilutil.py
Travis Oliphant authored
355 """
5255fcf Fixed imshow for RGBA images on UNIX. Fixed bug in std.
Travis Oliphant authored
356 im = toimage(arr)
e441986 @stefanv Clean up misc.pilutil.imshow.
stefanv authored
357 fnum,fname = tempfile.mkstemp('.png')
358 try:
359 im.save(fname)
360 except:
361 raise RuntimeError("Error saving temporary image data.")
362
363 import os
364 os.close(fnum)
365
366 cmd = os.environ.get('SCIPY_PIL_IMAGE_VIEWER','see')
367 status = os.system("%s %s" % (cmd,fname))
368
369 os.unlink(fname)
370 if status != 0:
371 raise RuntimeError('Could not execute image viewer.')
7b5f7fe Added resize and filter to pilutil.py
Travis Oliphant authored
372
30cd350 Remove duplicate imresize in pilutil.py and merge functionality.
Travis Oliphant authored
373 def imresize(arr, size, interp='bilinear', mode=None):
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
374 """
375 Resize an image.
376
377 Parameters
378 ----------
05b26a5 @rgommers DOC: merge wiki edits, lib, io, misc modules and main docstring.
rgommers authored
379 arr : ndarray
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
380 The array of image to be resized.
381
382 size : int, float or tuple
383 * int - Percentage of current size.
384 * float - Fraction of current size.
385 * tuple - Size of the output image.
386
b853c34 @rgommers DOC: merge doc wiki edits. Thanks to everyone who contributed.
rgommers authored
387 interp : str
388 Interpolation to use for re-sizing ('nearest', 'bilinear', 'bicubic'
389 or 'cubic').
30cd350 Remove duplicate imresize in pilutil.py and merge functionality.
Travis Oliphant authored
390
b853c34 @rgommers DOC: merge doc wiki edits. Thanks to everyone who contributed.
rgommers authored
391 mode : str
392 The PIL image mode ('P', 'L', etc.).
30cd350 Remove duplicate imresize in pilutil.py and merge functionality.
Travis Oliphant authored
393
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
394 Returns
395 -------
b853c34 @rgommers DOC: merge doc wiki edits. Thanks to everyone who contributed.
rgommers authored
396 imresize : ndarray
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
397 The resized array of image.
7b5f7fe Added resize and filter to pilutil.py
Travis Oliphant authored
398
399 """
30cd350 Remove duplicate imresize in pilutil.py and merge functionality.
Travis Oliphant authored
400 im = toimage(arr, mode=mode)
7b5f7fe Added resize and filter to pilutil.py
Travis Oliphant authored
401 ts = type(size)
6d3bfdc @stefanv Fix imresize, add test.
stefanv authored
402 if issubdtype(ts,int):
7b5f7fe Added resize and filter to pilutil.py
Travis Oliphant authored
403 size = size / 100.0
6d3bfdc @stefanv Fix imresize, add test.
stefanv authored
404 elif issubdtype(type(size),float):
405 size = (array(im.size)*size).astype(int)
7b5f7fe Added resize and filter to pilutil.py
Travis Oliphant authored
406 else:
407 size = (size[1],size[0])
30cd350 Remove duplicate imresize in pilutil.py and merge functionality.
Travis Oliphant authored
408 func = {'nearest':0,'bilinear':2,'bicubic':3,'cubic':3}
409 imnew = im.resize(size, resample=func[interp])
7b5f7fe Added resize and filter to pilutil.py
Travis Oliphant authored
410 return fromimage(imnew)
411
b71bc89 @pearu 1) Finished applying ppimport hooks to scipy.
pearu authored
412
7b5f7fe Added resize and filter to pilutil.py
Travis Oliphant authored
413 def imfilter(arr,ftype):
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
414 """
415 Simple filtering of an image.
416
417 Parameters
418 ----------
419 arr : ndarray
420 The array of Image in which the filter is to be applied.
421 ftype : str
422 The filter that has to be applied. Legal values are:
423 'blur', 'contour', 'detail', 'edge_enhance', 'edge_enhance_more',
424 'emboss', 'find_edges', 'smooth', 'smooth_more', 'sharpen'.
425
426 Returns
427 -------
b853c34 @rgommers DOC: merge doc wiki edits. Thanks to everyone who contributed.
rgommers authored
428 imfilter : ndarray
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
429 The array with filter applied.
430
431 Raises
432 ------
433 ValueError
05b26a5 @rgommers DOC: merge wiki edits, lib, io, misc modules and main docstring.
rgommers authored
434 *Unknown filter type.* If the filter you are trying
bb914a4 @rgommers DOC: merge wiki edits - misc module.
rgommers authored
435 to apply is unsupported.
7b5f7fe Added resize and filter to pilutil.py
Travis Oliphant authored
436
437 """
b71bc89 @pearu 1) Finished applying ppimport hooks to scipy.
pearu authored
438 _tdict = {'blur':ImageFilter.BLUR,
439 'contour':ImageFilter.CONTOUR,
440 'detail':ImageFilter.DETAIL,
441 'edge_enhance':ImageFilter.EDGE_ENHANCE,
442 'edge_enhance_more':ImageFilter.EDGE_ENHANCE_MORE,
443 'emboss':ImageFilter.EMBOSS,
444 'find_edges':ImageFilter.FIND_EDGES,
445 'smooth':ImageFilter.SMOOTH,
446 'smooth_more':ImageFilter.SMOOTH_MORE,
447 'sharpen':ImageFilter.SHARPEN
448 }
449
7b5f7fe Added resize and filter to pilutil.py
Travis Oliphant authored
450 im = toimage(arr)
cacf46d @pv PY23: misc: remove unnecessary list()'s
pv authored
451 if ftype not in _tdict.keys():
e2ed1e0 ENH: misc: update 'raise' statements
warren.weckesser authored
452 raise ValueError("Unknown filter type.")
7b5f7fe Added resize and filter to pilutil.py
Travis Oliphant authored
453 return fromimage(im.filter(_tdict[ftype]))
ebea7bf Run reindent.py (script distributed with Python) over the source to r…
cookedm authored
454
455
5549cde Added radon transform and bug fixes.
Travis Oliphant authored
456 def radon(arr,theta=None):
017f038 @rgommers DOC: update documentation for deprecated functionality not removed in…
rgommers authored
457 """`radon` is deprecated in scipy 0.11, and will be removed in 0.13
6779fb1 @rgommers DEP: misc: deprecate misc.radon.
rgommers authored
458
459 For this functionality, please use the "radon" function in scikits-image.
460
461 """
5549cde Added radon transform and bug fixes.
Travis Oliphant authored
462 if theta is None:
463 theta = mgrid[0:180]
bfded84 misc/: convert from typecodes to dtypes
cookedm authored
464 s = zeros((arr.shape[1],len(theta)), float)
5549cde Added radon transform and bug fixes.
Travis Oliphant authored
465 k = 0
466 for th in theta:
467 im = imrotate(arr,-th)
b71bc89 @pearu 1) Finished applying ppimport hooks to scipy.
pearu authored
468 s[:,k] = sum(im,axis=0)
5549cde Added radon transform and bug fixes.
Travis Oliphant authored
469 k += 1
470 return s
6779fb1 @rgommers DEP: misc: deprecate misc.radon.
rgommers authored
471
472
473 radon = numpy.deprecate(radon)
Something went wrong with that request. Please try again.