python矩阵变成图片_python 图像转矩阵,矩阵转图像

这篇博客介绍了如何在Python中将图像转换为矩阵以及如何将矩阵还原为图像。使用numpy的asarray函数可以将图像转换成矩阵,而PIL库的Image.fromarray函数则能将矩阵转换回图像。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值