title: How to avoid getting "out of range" IndexError while looping an image and accessing adjacent pixels of a specific coordinate?
body: <p>I'm trying access the adjacent pixels of a specific coordinate when looping a photo in order to get the RGB color but in some cases I get a <code>IndexError: image index out of range</code>. I tried avoiding this using some conditionals but didn't work. I would like to know how to prevent this error.</p>
  <pre><code>img = Image.open('Images/test.jpg')
  width, height = img.size
  pixel_distance = 1
  
  for x in range(width):
    for y in range(height):
  
      if y - pixel_distance &lt; 0:
          continue
      if y + pixel_distance &lt; height:
          continue
      if x - pixel_distance &lt; 0:
          continue
      if x + pixel_distance &gt; width:
          continue
  
      r, g, b = img.getpixel((x, y))  # Center pixel
      r1, g1, b1 = img.getpixel((x, y + pixel_distance))  # Bottom pixel
      r2, g2, b2 = img.getpixel((x, y - pixel_distance))  # Top pixel
      r3, g3, b3 = img.getpixel((x + pixel_distance, y))  # Right pixel
      r4, g4, b4 = img.getpixel((x - pixel_distance, y))  # Left pixel
  
      r5, g5, b5 = img.getpixel((x + pixel_distance, y + pixel_distance))  # Bottom right pixel
      r6, g6, b6 = img.getpixel((x + pixel_distance, y - pixel_distance))  # Top right pixel
      r7, g7, b7 = img.getpixel((x - pixel_distance, y - pixel_distance))  # Top left pixel
      r8, g8, b8 = img.getpixel((x - pixel_distance, y + pixel_distance))  # Bottom left pixel
  </code></pre>