[英]How to change the color of a pixel using PIL?
I was trying to change pixel of an image in python using this question. 我正在尝试使用此问题更改python中图像的像素。 If
mode
is 0, it changes first pixel in top right corner of image to grey(#C8C8C8). 如果
mode
为0,它将图像右上角的第一个像素更改为灰色(#C8C8C8)。 But it doesn't change. 但这并没有改变。 There is not enough documentation about
draw.point()
. 关于
draw.point()
文档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
Is using PIL
a must in your case? 您是否需要使用
PIL
? If not then consider using OpenCV ( cv2
) for altering particular pixels of image. 如果没有,那么可以考虑使用的OpenCV(
cv2
)为改变图像的特定像素。 Code which alter (0,0) pixel to (200,200,200) looks following way in opencv: 在opencv中,将(0,0)像素更改为(200,200,200)的代码如下所示:
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. 请注意,这段代码保存图像
.bmp
格式- CV2也可以写.jpg
图像,但为JPG通常是有损格式,一些小细节可能会丢失。 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
. 请记住,在
cv2
[0][0]
位于左上角,第一个值是像素的y坐标,而第二个值是x坐标,另外,颜色是BGR
顺序中从0
到255
(包括)的三个值,而不是BGR
顺序RGB
。
For OpenCV tutorials, including installation see this . 有关OpenCV教程(包括安装)的信息,请参见this 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.