I need to change pixel color of an image in python. Except for the pixel value (255, 0, 0) red I need to change every pixel color value into black (0, 0, 0). I tried the following code but it doesn't helped.
from PIL import Image
im = Image.open('A:\ex1.jpg')
for pixel in im.getdata():
if pixel == (255,0,0):
print "Red coloured pixel"
else:
pixel = [0, 0, 0]
Create a Color object bypassing the new RGB values as parameters. Get the pixel value from the color object using the getRGB() method of the Color class. Set the new pixel value to the image by passing the x and y positions along with the new pixel value to the setRGB() method.
The library encourages adding support for newer formats in the library by creating new file decoders. The basic difference between OpenCV image and PIL image is OpenCV follows BGR color convention and PIL follows RGB color convention and the method of converting will be based on this difference.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With