File: imagetools.py

package info (click to toggle)
psychopy 1.83.04.dfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 24,044 kB
  • ctags: 14,807
  • sloc: python: 84,668; makefile: 293; php: 49; sh: 23; xml: 9
file content (66 lines) | stat: -rw-r--r-- 1,700 bytes parent folder | download
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
#!/usr/bin/env python2

# Part of the PsychoPy library
# Copyright (C) 2015 Jonathan Peirce
# Distributed under the terms of the GNU General Public License (GPL).

'''Functions and classes related to image handling'''

try:
    from PIL import Image
except ImportError:
    import Image

import numpy

from psychopy.tools.typetools import float_uint8


def array2image(a):
    """Takes an array and returns an image object (PIL)"""
    # fredrik lundh, october 1998
    #
    # fredrik@pythonware.com
    # http://www.pythonware.com
    #
    if a.dtype.kind in ['u','I', 'B']:
        mode = "L"
    elif a.dtype.kind == numpy.float32:
        mode = "F"
    else:
        raise ValueError, "unsupported image mode"
    try:
        im = Image.fromstring(mode, (a.shape[1], a.shape[0]), a.tostring())
    except Exception:
        im = Image.frombytes(mode, (a.shape[1], a.shape[0]), a.tostring())
    return im


def image2array(im):
    """Takes an image object (PIL) and returns a numpy array
    """
#     fredrik lundh, october 1998
#
#     fredrik@pythonware.com
#     http://www.pythonware.com

    if im.mode not in ("L", "F"):
        raise ValueError, "can only convert single-layer images"
    try:
        imdata = im.tostring()
    except Exception:
        imdata = im.tobytes()
    if im.mode == "L":
        a = numpy.fromstring(imdata, numpy.uint8)
    else:
        a = numpy.fromstring(imdata, numpy.float32)

    a.shape = im.size[1], im.size[0]
    return a


def makeImageAuto(inarray):
    """Combines float_uint8 and image2array operations
    ie. scales a numeric array from -1:1 to 0:255 and
    converts to PIL image format"""
    return image2array(float_uint8(inarray))