Skip to main content
 首页 » 编程设计

python之将图像转换为像素阵列

2024年12月31日7mate10pro

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

致力于谷歌协作。

它显示一条错误消息:TypeError: 'numpy.uint8' object is not iterable

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)   

请您参考如下方法:

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

plt.imread('papa.png') 

或者您可以使用以下方法转换您的 PIL 图像:

img = np.asarray(pil_im)