| 1 |
import numpy as np |
| 2 |
from PIL import ImageFont |
| 3 |
|
| 4 |
|
| 5 |
class ImageColorGenerator(object): |
| 6 |
"""Color generator based on a color image. |
| 7 |
|
| 8 |
Generates colors based on an RGB image. A word will be colored using |
| 9 |
the mean color of the enclosing rectangle in the color image. |
| 10 |
|
| 11 |
After construction, the object acts as a callable that can be passed as |
| 12 |
color_func to the word cloud constructor or to the recolor method. |
| 13 |
|
| 14 |
Parameters |
| 15 |
---------- |
| 16 |
image : nd-array, shape (height, width, 3) |
| 17 |
Image to use to generate word colors. Alpha channels are ignored. |
| 18 |
This should be the same size as the canvas. for the wordcloud. |
| 19 |
default_color : tuple or None, default=None |
| 20 |
Fallback colour to use if the canvas is larger than the image, |
| 21 |
in the format (r, g, b). If None, raise ValueError instead. |
| 22 |
""" |
| 23 |
# returns the average color of the image in that region |
| 24 |
def __init__(self, image, default_color=None): |
| 25 |
if image.ndim not in [2, 3]: |
| 26 |
raise ValueError("ImageColorGenerator needs an image with ndim 2 or" |
| 27 |
" 3, got %d" % image.ndim) |
| 28 |
if image.ndim == 3 and image.shape[2] not in [3, 4]: |
| 29 |
raise ValueError("A color image needs to have 3 or 4 channels, got %d" |
| 30 |
% image.shape[2]) |
| 31 |
self.image = image |
| 32 |
self.default_color = default_color |
| 33 |
|
| 34 |
def __call__(self, word, font_size, font_path, position, orientation, **kwargs): |
| 35 |
"""Generate a color for a given word using a fixed image.""" |
| 36 |
# get the font to get the box size |
| 37 |
font = ImageFont.truetype(font_path, font_size) |
| 38 |
transposed_font = ImageFont.TransposedFont(font, |
| 39 |
orientation=orientation) |
| 40 |
# get size of resulting text |
| 41 |
box_size = transposed_font.getbbox(word) |
| 42 |
x = position[0] |
| 43 |
y = position[1] |
| 44 |
# cut out patch under word box |
| 45 |
patch = self.image[x:x + box_size[2], y:y + box_size[3]] |
| 46 |
if patch.ndim == 3: |
| 47 |
# drop alpha channel if any |
| 48 |
patch = patch[:, :, :3] |
| 49 |
if patch.ndim == 2: |
| 50 |
raise NotImplementedError("Gray-scale images TODO") |
| 51 |
# check if the text is within the bounds of the image |
| 52 |
reshape = patch.reshape(-1, 3) |
| 53 |
if not np.all(reshape.shape): |
| 54 |
if self.default_color is None: |
| 55 |
raise ValueError('ImageColorGenerator is smaller than the canvas') |
| 56 |
return "rgb(%d, %d, %d)" % tuple(self.default_color) |
| 57 |
color = np.mean(reshape, axis=0) |
| 58 |
return "rgb(%d, %d, %d)" % tuple(color) |