Ver Nick
Ver Nick

Reputation: 253

How to change the color of a pixel using PIL?

I was trying to change pixel of an image in python using this question. If mode is 0, it changes first pixel in top right corner of image to grey(#C8C8C8). But it doesn't change. There is not enough documentation about draw.point(). What is the problem with this code?

import random
from PIL import Image, ImageDraw
mode = 0
image = Image.open("dom.jpg") 
draw = ImageDraw.Draw(image)  
width = image.size[0]  
height = image.size[1]      
pix = image.load()
string = "kod"
n = 0
if (mode == 0):
    draw.point((0, 0), (200, 200, 200))
if(mode == 1):
    print(pix[0,0][0])
image.save("dom.jpg", "JPEG")
del draw

Upvotes: 0

Views: 1823

Answers (1)

Daweo
Daweo

Reputation: 36360

Is using PIL a must in your case? If not then consider using OpenCV (cv2) for altering particular pixels of image. Code which alter (0,0) pixel to (200,200,200) looks following way in opencv:

import cv2
img = cv2.imread('yourimage.jpg')
height = img.shape[0]
width = img.shape[1]
img[0][0] = [200,200,200]
cv2.imwrite('newimage.bmp',img)

Note that this code saves image in .bmp format - cv2 can also write .jpg images, but as jpg is generally lossy format, some small details might be lost. Keep in mind that in cv2 [0][0] is left upper corner and first value is y-coordinate of pixel, while second is x-coordinate, additionally color are three values from 0 to 255 (inclusive) in BGR order rather than RGB.

For OpenCV tutorials, including installation see this.

Upvotes: 1

Related Questions