【问题标题】:How can I get the pixels matrix of an image without using numpy?如何在不使用 numpy 的情况下获取图像的像素矩阵?
【发布时间】:2017-06-14 23:35:36
【问题描述】:

我想找到一种不使用numpy 来获取像素矩阵的方法。我知道与代码一起使用

from PIL import Image  

import numpty as np  

img = Image.open('example.png', 'r')  

pixels = np.array(img)

pixels获取图像的像素矩阵。但是,我想找到一种不使用numpy 来获取像素图像而不使用包numpy 的方法。提前致谢!

【问题讨论】:

    标签: image python-2.7 numpy matrix python-imaging-library


    【解决方案1】:

    您可以使用Image 方法getdata(band=None)getpixel(xy)

    In [1]: from PIL import Image
    
    In [2]: im = Image.open('block.png', 'r')
    
    In [3]: data = list(im.getdata())
    
    In [4]: data[:20]
    Out[4]: 
    [(0, 0, 0),
     (0, 0, 0),
     (0, 0, 0),
     (0, 0, 0),
     (0, 0, 0),
     (0, 0, 0),
     (0, 0, 0),
     (0, 0, 0),
     (0, 0, 0),
     (0, 0, 0),
     (0, 0, 0),
     (144, 33, 33),
     (144, 33, 33),
     (144, 33, 33),
     (144, 33, 33),
     (255, 255, 255),
     (255, 255, 255),
     (255, 255, 255),
     (255, 255, 255),
     (0, 0, 0)]
    
    In [5]: pxl = im.getpixel((1, 1))
    
    In [6]: pxl
    Out[6]: (144, 33, 33)
    

    要将getdata() 返回的序列转换为列表列表,可以使用列表推导:

    In [61]: data2d = [data[i:i+im.width] for i in range(0, len(data), im.width)]
    
    In [62]: data2d[0]  # row 0
    Out[62]: 
    [(0, 0, 0),
     (0, 0, 0),
     (0, 0, 0),
     (0, 0, 0),
     (0, 0, 0),
     (0, 0, 0),
     (0, 0, 0),
     (0, 0, 0),
     (0, 0, 0),
     (0, 0, 0)]
    
    In [63]: data2d[1]  # row 1
    Out[63]: 
    [(0, 0, 0),
     (144, 33, 33),
     (144, 33, 33),
     (144, 33, 33),
     (144, 33, 33),
     (255, 255, 255),
     (255, 255, 255),
     (255, 255, 255),
     (255, 255, 255),
     (0, 0, 0)]
    
    In [64]: data2d[1][1]
    Out[64]: (144, 33, 33)
    

    【讨论】:

    • 感谢您的回答!但是是否可以将矩阵作为列表列表获取?我的意思是,array(pixels) 的方式,因为 list(im.getdata()) 只是一个列表,不是吗?
    • 我没有看到 Image 自动执行此操作的方法,但您可以使用标准 python 轻松完成;查看我的更新答案。
    猜你喜欢
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    相关资源
    最近更新 更多