Python 3: 输出 R,G,B 到 CSV - 索引错误:图像索引超出范围

2024-03-28 19:27:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用PIL模块将图像的R,G,B值输出到csv,但是我成功地将RGB输出到csv,但是我不明白为什么会遇到“索引错误:图像索引超出范围”。我怀疑我当前的值是否不准确,我似乎无法找出原因。下面是我使用的代码。你知道吗

from PIL import Image #Imported PIL Module

im = Image.open('Desktop/Img001.jpg') #Opened image from path

img_width = 255
img_height = 255 
img_width, img_height, = im.size #Size of the image I want
pix = im.load() # loading the pixel value

with open('output_file.csv', 'w+') as f:  #made a new csv file to load
                                             #the pixel value.

  f.write('R,G,B\n') #write the image pixel in RGB row/col

  for x in range(img_width):           #for loop x as img_width 
    for y in range(img_height):        #for loop y as img_height
      r = pix[x,y][0]                  #load r with pixel x,y 
      g = pix[x,x][1]                  #load g with pixel x,x
      b = pix[x,x][2]                  #load b with pixel x,x
      f.write('{0},{1},{2}\n'.format(r,g,b))     #format as r,g,b

下面是它输出到csv文件时得到的结果。

enter image description here


Tags: csvtheimageimgforpilaswith
1条回答
网友
1楼 · 发布于 2024-03-28 19:27:57

您输入了一个拼写错误,而不是:

  r = pix[x,y][0]                  #load r with pixel x,y 
  g = pix[x,x][1]                  #load g with pixel x,x
  b = pix[x,x][2]                  #load b with pixel x,x

你想要:

  r = pix[x,y][0]
  g = pix[x,y][1]
  b = pix[x,y][2]

相关问题 更多 >