Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python imaging library: Can I simply fill my image with one color?

Tags:

python

image

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

like image 923
Antonio Avatar asked Dec 12 '13 16:12

Antonio


People also ask

Is Pil and Pillow the same?

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.

What does PIL mean in Python?

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.


2 Answers

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]])
like image 97
ryrich Avatar answered Sep 17 '22 15:09

ryrich


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)

like image 31
Antonio Avatar answered Sep 20 '22 15:09

Antonio