"有没有更好的方法获得RGB矩阵?"

2024-06-28 19:18:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个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)


Tags: 项目inimage程序noneimgforreturn
1条回答
网友
1楼 · 发布于 2024-06-28 19:18:59

不需要做任何显式循环。。。您可以直接将图像转换为numpy数组

import numpy
from PIL import Image
img = numpy.uint8(Image.open("myimage.jpg"))
h, w, _ = img.shape

那么

r, g, b = img[y][x]

相关问题 更多 >