I googled, checked the documentation of PIL library and much more, but I couldn't find the answer to my simple question: how can I fill an existing image with a desired color?
(I am using from PIL import Image
and from PIL import ImageDraw
)
This command creates a new image filled with a desired color
image = Image.new("RGB", (self.width, self.height), (200, 200, 200))
But I would like to reuse the same image without the need of calling "new" every time
What is PIL/Pillow? PIL (Python Imaging Library) adds many image processing features to Python. Pillow is a fork of PIL that adds some user-friendly features.
PIL stands for Python Imaging Library, and it's the original library that enabled Python to deal with images. PIL was discontinued in 2011 and only supports Python 2. To use its developers' own description, Pillow is the friendly PIL fork that kept the library alive and includes support for Python 3.
Have you tried:
image.paste(color, box)
where box
can be a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0))
Since you want to fill the entire image, you can use the following:
image.paste( (200,200,200), [0,0,image.size[0],image.size[1]])
One possibility is to draw a rectangle:
from PIL import Image
from PIL import ImageDraw
#...
draw = ImageDraw.Draw(image)
draw.rectangle([(0,0),image.size], fill = (200,200,200) )
Or (untested):
draw = ImageDraw.Draw(image).rectangle([(0,0),image.size], fill = (200,200,200) )
(Although it is surprising there is no simpler method to fill a whole image with one background color, like setTo
for opencv)
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