Sunday, August 18, 2024

Convert each pixel of one color to another color

# Convert each pixel of one color to another color

# Error value allows pixels +- that error value to also be converted


from PIL import Image


img = Image.open("Just.png")

img = img.convert("RGB")

pixels = img.load()


target_color = (237, 238, 247)

replacement_color = (255, 255, 255)


width, height = img.size

error = 10 # Allowing for variation in pixel value


for x in range(width):

  for y in range(height):

    if pixels[x, y][0] >= target_color[0] - error and pixels[x, y][0] <= target_color[0] + error:

      if pixels[x, y][1] >= target_color[1] - error and pixels[x, y][1] <= target_color[1] + error:

        if pixels[x, y][2] >= target_color[2] - error and pixels[x, y][2] <= target_color[2] + error:

          pixels[x, y] = replacement_color


img.save("Converted.png")

img.show()


No comments:

Post a Comment