Changing pixel color value in PIL
Here is the way I'd use PIL to do what you want:
from PIL import Image
imagePath = 'A:\ex1.jpg'
newImagePath = 'A:\ex2.jpg'
im = Image.open(imagePath)
def redOrBlack (im):
newimdata = []
redcolor = (255,0,0)
blackcolor = (0,0,0)
for color in im.getdata():
if color == redcolor:
newimdata.append( redcolor )
else:
newimdata.append( blackcolor )
newim = Image.new(im.mode,im.size)
newim.putdata(newimdata)
return newim
redOrBlack(im).save(newImagePath)
See this wikibook: https://en.wikibooks.org/wiki/Python_Imaging_Library/Editing_Pixels
Modifying that code to fit your problem:
pixels = img.load() # create the pixel map
for i in range(img.size[0]): # for every pixel:
for j in range(img.size[1]):
if pixels[i,j] != (255, 0, 0):
# change to black if not red
pixels[i,j] = (0, 0 ,0)
You could use img.putpixel
:
im.putpixel((x, y), (255, 0, 0))