python中rgb_python - 图像的RGB矩阵

Taking an image as input, how can I get the rgb matrix corresponding to it?

I checked out the numpy.asarray function. Does that give me the rgb matrix or some other matrix?

解决方案

The simplest answer is to use the NumPy and SciPy wrappers around PIL. There's a great tutorial, but the basic idea is:

from scipy import misc

arr = misc.imread('lena.png') # 640x480x3 array

arr[20, 30] # 3-vector for a pixel

arr[20, 30, 1] # green value for a pixel

For a 640x480 RGB image, this will give you a 640x480x3 array of uint8.

Or you can just open the file with PIL (or, rather, Pillow; if you're still using PIL, this may not work, or may be very slow) and pass it straight to NumPy:

import numpy as np

from PIL import Image

img = Image.open('lena.png')

arr = np.array(img) # 640x480x4 array

arr[20, 30] # 4-vector, just like above

This will give you a 640x480x4 array of type uint8 (the 4th is alpha; PIL always loads PNG files as RGBA, even if they have no transparency; see img.getbands() if you're every unsure).

If you don't want to use NumPy at all, PIL's own PixelArray type is a more limited array:

arr = img.load()

arr[20, 30] # tuple of 4 ints

This gives you a 640x480 PixelAccess array of RGBA 4-tuples.

Or you can just call getpixel on the image:

img.getpixel(20, 30) # tuple of 4 ints

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值