python - RGB matrix of an image

后端 未结 5 1104
花落未央
花落未央 2020-12-24 13:02

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?

5条回答
  •  一生所求
    2020-12-24 13:38

    You can do that with Pillow, the getdata method gives you a flat array of the pixels, you can then build a matrix from that using the size of the image.

    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)]
    

提交回复
热议问题