将图像转换为像素阵列

时间:2019-02-02 07:03:35

标签: python numpy image-recognition

我正在尝试将灰度图像的像素转换为numpy数组。

使用Google Colab。

它显示一条错误消息:TypeError:'numpy.uint8'对象不可迭代

enter code here

    ##load Library
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.image as mpimg
    from google.colab import files
    from scipy import misc #to see image
    from sklearn.model_selection import train_test_split
    from sklearn.linear_model import LogisticRegression

    from PIL import Image
    pil_im = Image.open('papa.png')
    pil_imgray = pil_im.convert('LA')

    img = np.array(list(pil_imgray.getdata(band=0)), float)
    img.shape = (pil_imgray.size[1], pil_imgray.size[0])
    plt.imshow(img)

    for eachRow in img:
      for eachPixel in eachRow:
          x_test.append(sum(eachPixel)/3.0)  

1 个答案:

答案 0 :(得分:1)

您可以使用matplotlib直接加载图像:

plt.imread('papa.png')

或者您可以使用以下方式转换PIL图片:

img = np.asarray(pil_im)