Q:

Python 3: Output R,G,B to CSV - Index Error: Image Index out of range

I'm trying to output the R,G,B value of an image to csv using PIL module, however I successfully output the RGB to a csv but I'm confused why I encountered an "Index Error: Image index out of range." and I doubt that the value I currently have is inaccurate and I can't seem to figure out why. Here is my code below that I used.
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

Below is what I got when it outputs to a csv file.

A:

You have a typo, instead of:
  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

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

