22

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.

wovano
  • 4,543
  • 5
  • 22
  • 49
Antonio
  • 19,451
  • 13
  • 99
  • 197

2 Answers2

20

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]))
wovano
  • 4,543
  • 5
  • 22
  • 49
ryrich
  • 2,164
  • 16
  • 24
3

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)

Antonio
  • 19,451
  • 13
  • 99
  • 197