代码之家  ›  专栏  ›  技术社区  ›  mikanim

使用pil从图像中获取像素

  •  0
  • mikanim  · 技术社区  · 7 年前

    我想写一个脚本,读取一个BMP文件,然后记录X-Y轴上的像素,其中图像不是白色。然后,使用这些数据,将其保存到.txt文件中。

    我已经开始使用枕头库,但还没有找到解决这个问题的方法。我打开了带枕头的BMP文件,试着在图片中的模块上玩,但是我找不到如何使其工作。

    事先谢谢!

    2 回复  |  直到 7 年前
        1
  •  1
  •   Aivaras Kazakevičius    7 年前

    您可以使用 Image.getpixel() 从PIL。

    下面的代码将以二维列表的形式提供所有非白色像素。

    from PIL import Image
    
    im = Image.open('x.bmp')
    
    imageSizeW, imageSizeH = im.size
    
    nonWhitePixels = []
    
    for i in range(1, imageSizeW):
        for j in range(1, imageSizeH):
            pixVal = im.getpixel((i, j))
            if pixVal != (255, 255, 255):
                nonWhitePixels.append([i, j])
    
    print(nonWhitePixels)
    
        2
  •  1
  •   SpghttCd    7 年前

    编辑: 刚刚意识到,问题是找到所有像素的索引 不同的 从白色…
    对于这种情况,只需将布尔数组的计算替换为其补码函数:

    white = (img[:, :, :3] != 255).any(2)
    

    简单添加 ~ 在布尔数组前面 np.where :

    coords = np.array(np.where(~white))[::-1].T
    

    因此,测试结果正好相反。

    enter image description here


    这里我假设 “使用PIL” 这不是一个严格的要求,但只是一个你试图开始的迹象。

    也就是说,您可以使用 imread imageio :

    import numpy as np
    from imageio import imread
    
    img = imread(filename)
    white = (img[:, :, :3] == 255).all(2)
    coords = np.array(np.where(white))[::-1].T
    

    写入一个ASCII文件可以这样做

    with open('xycoordinates.txt', 'w') as f:
        for c in coords:
            f.write(f'{c[0]},{c[1]}\n')
    

    解释
    img 是一个三维数组,形状为 (nr, nc, c) ,即行数、列数和rgba值。
    img[:, :, :3] == 255 返回形状相同的布尔数组,如 IMG ,表示单个RGB值的组件匹配(不涉及A。如果A也应为255,只需去掉完整的索引括号)。
    .all(2) 将其缩小到所需的形状数组 (nr, nc) 只将这些索引设置为 True ,其中完整的rgba数组匹配。

    np.where(white) 返回行和列索引的元组。
    np.array() 将其强制转换为numpy数组,以便对其应用numpy索引和转换。
    AS row/column 是A的相反顺序 x/y 命名法, [::-1] 反转两个索引数组的顺序。 转换方式 .T 不输出两个数组( x y )n个索引,但n个数组 (x, y) 指数。

    例子

    img = imread(samplefile)
    plt.imshow(img)
    

    enter image description here

    white = (img == [255, 255, 255, 255]).all(2)
    
    array([[False, False,  True, False, False, False],
           [False, False,  True,  True, False, False],
           [False,  True, False, False, False, False],
           [ True,  True, False, False, False, False],
           [False, False, False, False, False,  True]])
    
    coords = np.array(np.where(white))[::-1].T
    
    array([[2, 0],
           [2, 1],
           [3, 1],
           [1, 2],
           [0, 3],
           [1, 3],
           [5, 4]], dtype=int64)
    
    plt.plot(*coords.T, 'ro')
    

    enter image description here

    推荐文章