简体   繁体   English

使用PIL为jpg图像着色

[英]coloring a jpg image using PIL

I have written a python code using PIL and Tkinter where I display an image and put a red circle on the image where a user clicked. 我使用PIL和Tkinter编写了python代码,在其中显示图像,并在用户单击的图像上放置了一个红色圆圈。 Here is the relevant code. 这是相关的代码。

def paint_img(event, canvas):
    x, y = event.x, event.y
    image_draw.ellipse((x-10, y-10, x+10, y+10), fill='red')
    canvas._image_tk = ImageTk.PhotoImage(pilImg)
    canvas.itemconfigure(canvas._image_id, image=canvas._image_tk)

It seems that it works with some images, but in some cases it displays a grey circle. 似乎它适用于某些图像,但在某些情况下,它会显示一个灰色圆圈。 I used identify on the test images, for the successful one the output is 我在测试图像上使用了identify ,对于成功的图像,输出为

totestcolor.jpg JPEG 561x549 561x549+0+0 8-bit DirectClass 18.3kb 

for the unsuccessful one, the output is: 对于不成功的,输出为:

totestcolor1.jpg JPEG 1533x1095 1533x1095+0+0 8-bit PseudoClass 256c 70.4kb  

I want to know why this is happening and if there is any way to output a red circle for the unsuccessful image as well. 我想知道为什么会这样,以及是否还有办法为失败的图像输出红色圆圈。

That's because the original image is grayscale. 那是因为原始图像是灰度的。 You can convert it to full RGB before drawing the red circle. 您可以在绘制红色圆圈之前将其转换为全RGB。 In the PIL library, it is code like this: 在PIL库中,是这样的代码:

pilImg = pilImg.convert("RGB")   # or "RGBA" to keep transparency

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM