python - 有没有更好的方法来获得 rgb 矩阵?
问题描述
我正在尝试创建一个 python 程序来获取一些图像并将其转换为 ASCII 艺术。
该项目取自Robert Heaton网页,他在该网页上提出了一些编程项目来培养您的技能。
好吧,有一次,我必须从每个像素中获取 rgb 值并将它们存储在矩阵中,我认为这可以比我做得更好。这是我的代码:
def extractPixels(img=None):
'''
This function will receive a Image object and return
a 2D matrix containing pixels information
'''
if(type(img) == None or not(Image.isImageType(img))):
raise TypeArgumentError("You have to pass a Image object")
dataMatrix = []
auxList = []
for i in range(0, img.width, 1):
for j in range(0, img.height, 1):
auxList.append(img.getpixel((i,j)))
dataMatrix.append(auxList)
auxList = []
return dataMatrix
我正在使用Pillow库进行图像处理。
这段代码
img.getpixel(i,j)
将返回每个像素的元组 (R,G,B)。
解决方案
无需执行任何显式循环...您可以直接将图像转换为numpy
数组
import numpy
from PIL import Image
img = numpy.uint8(Image.open("myimage.jpg"))
h, w, _ = img.shape
然后
r, g, b = img[y][x]