Exemple #1
0
 def replace_color(self, color1, color2, ignore_alpha=False):
     """Return an image with color1 replaced by color2. Requires numpy."""
     if 'RGB' not in self.mode:
         raise NotImplementedError("replace_color expects RGB/RGBA image")
     n = 3 if (self.mode == 'RGB' or ignore_alpha) else 4
     color1 = ImageColor.getrgba(color1)[:n]
     color2 = ImageColor.getrgba(color2)[:n]
     data = np.array(self)
     mask = _nparray_mask_by_color(data, color1, n)
     data[:, :, :n][mask] = color2
     return Image.fromarray(data)
Exemple #2
0
 def from_text(cls,
               text,
               font,
               fg="black",
               bg=None,
               padding=0,
               max_width=None,
               line_spacing=0,
               align="left",
               tokenizer=whitespace_span_tokenize,
               hyphenator=None):
     """Create image from text. If max_width is set, uses the tokenizer and optional hyphenator
     to split text across multiple lines."""
     padding = Padding(padding)
     if bg is None:
         bg = ImageColor.getrgba(fg)._replace(alpha=0)
     if max_width is not None:
         text = ImageDraw.word_wrap(text, font, max_width, tokenizer,
                                    hyphenator)
     w, h = ImageDraw.textsize(text, font, spacing=line_spacing)
     if max_width is not None and w > max_width:
         logger.warning("Text cropped as too wide to fit: {}".format(text))
         w = max_width
     img = Image.new("RGBA", (w + padding.x, h + padding.y), bg)
     draw = ImageDraw.Draw(img)
     draw.text((padding.l, padding.u),
               text,
               font=font,
               fill=fg,
               spacing=line_spacing,
               align=align)
     return img
Exemple #3
0
 def select_color(self, color):
     """Return a transparency mask selecting a color in an image. Requires numpy."""
     if 'RGB' not in self.mode:
         raise NotImplementedError("replace_color expects RGB/RGBA image")
     data = np.array(self)
     color = ImageColor.getrgba(color)[:data.shape[-1]]
     mask = _nparray_mask_by_color(data, color)
     return Image.fromarray(mask * 255).convert("1")