gpt4 book ai didi

python - 图像的 RGB 矩阵

转载 作者:IT老高 更新时间:2023-10-28 20:53:18 27 4
gpt4 key购买 nike

以图像为输入,如何得到对应的rgb矩阵?我检查了 numpy.asarray 函数。这会给我rgb矩阵还是其他矩阵?

最佳答案

请注意,截至 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 数组(第 4 个是 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

关于python - 图像的 RGB 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25102461/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com