python - 图像的RGB矩阵 [英] python - RGB matrix of an image
问题描述
将图像作为输入,如何获得与之对应的rgb矩阵?
我检查了numpy.asarray函数。这给了我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?
推荐答案
最简单的答案是在PIL周围使用NumPy和SciPy包装器。有一个很棒的教程,但基本的想法是:
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
对于640x480 RGB图像,这将为您提供640x480x3的 uint8
数组。
For a 640x480 RGB image, this will give you a 640x480x3 array of uint8
.
或者你可以用PIL打开文件(或者更确切地说,Pillow;如果你还在使用PIL,这可能不起作用,或者可能非常慢)并直接传递给NumPy:
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
这将为您提供类型为 uint8
的640x480x4数组(第4个为alpha; PIL始终将PNG文件作为RGBA加载,即使它们有不透明;如果您不确定,请参阅 img.getbands()
。
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).
如果您不想使用NumPy,PIL自己的 PixelArray
类型是一个更有限的数组:
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
这给你一个640x480 PixelAccess
RGBA 4元组数组。
This gives you a 640x480 PixelAccess
array of RGBA 4-tuples.
或者你可以打电话给 getpixel
图片上:
Or you can just call getpixel
on the image:
img.getpixel(20, 30) # tuple of 4 ints
这篇关于python - 图像的RGB矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!