/usr/share/pyshared/numm/image.py is in python-numm 0.5-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | """
Conversion between image files and numpy arrays.
Images are represented as arrays with shape (height, width, 3).
"""
import numpy
import Image
def _get_dimensions(im, width, height):
"preserve aspect if width or height is None"
if width and height:
return (width, height)
aspect = im.size[0]/float(im.size[1])
if width:
return (width, int(width/aspect))
else:
return (int(height*aspect), height)
def image2np(path, width=None, height=None):
"Load an image file into an array."
im = Image.open(path)
if width or height:
im = im.resize(_get_dimensions(im, width, height), 1)
im = im.convert('RGB')
np = numpy.asarray(im, dtype=numpy.uint8)
return np
def np2image(np, path):
"Save an image array to a file."
assert np.dtype == numpy.uint8, "nparr must be uint8"
if len(np.shape) > 2 and np.shape[2] == 3:
mode = 'RGB'
else:
mode = 'L'
im = Image.fromstring(
mode, (np.shape[1], np.shape[0]), np.tostring())
im.save(path)
if __name__ == '__main__':
# XXX: Replace this with an automated test.
import sys
np1 = image2np(sys.argv[1])
np2image(np1, sys.argv[2])
np2 = image2np(sys.argv[2])
print 'error: ', numpy.sum(abs(np1-np2))
|