python 图像转矩阵,矩阵转图像

时间:2022-03-02 02:32:17

1、图像转换为矩阵

matrix = numpy.asarray(image)    
Help on function asarray in module numpy.core.numeric:

asarray(a, dtype=None, order=None)
Convert the input to an array. Parameters
----------
a : array_like
Input data, in any form that can be converted to an array. This
includes lists, lists of tuples, tuples, tuples of tuples, tuples
of lists and ndarrays.
dtype : data-type, optional
By default, the data-type is inferred from the input data.
order : {'C', 'F'}, optional
Whether to use row-major (C-style) or
column-major (Fortran-style) memory representation.
Defaults to 'C'. Returns
-------
out : ndarray
Array interpretation of `a`. No copy is performed if the input
is already an ndarray with matching dtype and order. If `a` is a
subclass of ndarray, a base class ndarray is returned. See Also
--------
asanyarray : Similar function which passes through subclasses.
ascontiguousarray : Convert input to a contiguous array.
asfarray : Convert input to a floating point ndarray.
asfortranarray : Convert input to an ndarray with column-major
memory order.
asarray_chkfinite : Similar function which checks input for NaNs and Infs.
fromiter : Create an array from an iterator.
fromfunction : Construct an array by executing a function on grid
positions.

2、矩阵转换为图像

image = Image.fromarray(matrix)
Help on function fromarray in module PIL.Image:

fromarray(obj, mode=None)
Creates an image memory from an object exporting the array interface
(using the buffer protocol). If obj is not contiguous, then the tobytes method is called
and :py:func:`~PIL.Image.frombuffer` is used. :param obj: Object with array interface
:param mode: Mode to use (will be determined from type if None)
See: :ref:`concept-modes`.
:returns: An image object. .. versionadded:: 1.1.6