python - 图像的RGB矩阵

问题描述 投票:19回答:6

将图像作为输入,如何获得与其对应的rgb矩阵?我检查了numpy.asarray函数。这会给我rgb矩阵或其他矩阵吗?

python image numpy python-imaging-library
6个回答
14
投票

请注意,此答案已于2018年过时; scipy已弃用imread,你应该改用imageio.imread。请参阅this transition doc关于两者之间的差异。如果您只是导入新库代替旧库,下面的代码应该没有任何更改,但我还没有测试过。


最简单的答案是在PIL周围使用NumPy和SciPy包装器。有a great tutorial,但基本的想法是:

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阵列。

或者你可以用PIL打开文件(或者更确切地说,Pillow;如果你还在使用PIL,这可能不起作用,或者可能非常慢)并直接传递给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阵列(第四个是alpha; PIL总是将PNG文件作为RGBA加载,即使它们没有透明度;如果您不确定,请参阅img.getbands())。

如果您根本不想使用NumPy,PIL自己的PixelArray类型是一个更有限的数组:

arr = img.load()
arr[20, 30] # tuple of 4 ints

这为您提供了640x480 PixelAccess RGBA 4元组阵列。

或者你可以在图像上调用getpixel

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

11
投票

我有一种感觉,我没有完全按照你的意愿去做,所以请说明这是否完全不合适。您可以像这样打开图像并获取像素数组:

import Image
im = Image.open('Lenna.png')
pixels = list(im.getdata())

这将为您提供一个看起来像的RGB数据的平面列表

[(226, 137, 125), (226, 137, 125), (223, 137, 133), (223, 136, 128), 
 (226, 138, 120), (226, 129, 116), (228, 138, 123), (227, 134, 124), 
 (227, 140, 127), (225, 136, 119), (228, 135, 126), (225, 134, 121),...

现在这将是一个平面数组中的所有像素,如果你想要一个二维数组,那么就需要一些额外的代码。不确定PIL中是否有直接功能。


1
投票

另外,如果您或其他任何人使用opencv,请添加。

 imgc=cv2.imread(file)

或以灰度读入

 imgc=cv2.imread(file,0)

如果您要对图像进行一些比较,您可能需要考虑将像素数组转换为直方图以规范化数据。

   hist = np.histogram(img.flatten(),256,[0,256])[0]

上面的行首先展平你的img数组,这样你就失去了图像的维度。然后它生成从0到256的二进制位(对于灰度图像)并将img中的计数添加到这些二进制数并将它们作为hist返回,然后可以绘制。例如,如果100 bin的值为20,则表示图像中的20个像素的值为100。

希望这为想要开始使用opencv的任何人提供另一种思考方式。


1
投票

我尝试了imageio.imread并且效果很好,但是一分钟之后偶然发现matplotlib中的一个函数完全相同,得到一个q由三个数组组成的numpy

from matplotlib import pyplot as plot
image = plt.imread(path)

0
投票

你可以用Pillow做到这一点,getdata方法为你提供了一个像素的平面数组,然后你可以使用图像的size构建一个矩阵。

from PIL import Image

def getPixels(filename):
    img = Image.open(filename, 'r')
    w, h = img.size
    pix = list(img.getdata())
    return [pix[n:n+w] for n in range(0, w*h, w)]

0
投票

谢谢abarenet!请使用imageio而不是scipy,因为scipy不再继续使用。简化abarnet的答案:

  1. 安装imageio pip3 install imageto
  2. python3代码: 如果图像的尺寸为260X340,则rgb_matrix是尺寸为260X340X3的数组 from imageio import imread rgb_matrix = imread('image13.png') print(rgb_matrix[15][23])
© www.soinside.com 2019 - 2024. All rights reserved.