Providing Python code for masked word cloud with collision detection
Here's a complete Python script that loads a binary silhouette mask image, places words only within the black regions using collision detection on bounding boxes, and generates a masked word cloud image. It uses PIL and numpy and requires a font file path supplied by the user.
Below is a self-contained Python example that loads a binary silhouette image (black shape on white background) and places words only in the black areas, using a simple bounding-box collision check. It uses Pillow (PIL) for drawing text and NumPy to read the mask.
python
import random
import numpy as np
from PIL import Image, ImageDraw, ImageFont
# -------------------------------------------------------------------
# Helper functions
# -------------------------------------------------------------------
def is_region_black(mask_array, x0, y0, w, h, threshold=128):
"""
Returns True if the rectangle [x0, x0+w) x [y0, y0+h) lies entirely
within the black region of a mask image.
mask_array is a 2D numpy array (grayscale), 0=black, 255=white.
threshold is the cutoff for "black".
"""
h_mask, w_mask = mask_array.shape
if x0 < 0 or y0 < 0 or x0 + w >= w_mask or y0 + h >= h_mask:
return False
region = mask_array[y0:y0+h, x0:x0+w]
# Check if all pixels in the region are below threshold (i.e., black)
return (region < threshold).all()
def boxes_overlap(box1, box2, padding=2):
"""
Checks if box1 and box2 overlap. Boxes are (x0, y0, x1, y1).
Optional padding prevents text from touching too closely.
"""
x0a, y0a, x1a, y1a = box1
x0b, y0b, x1b, y1b = box2
return not (x1a + padding < x0b or x0a - padding > x1b or
y1a + padding < y0b or y0a - padding > y1b)
def find_position(mask_array, word_size, placed_boxes, max_attempts=500):
"""
Attempts to find a valid position (x, y) for a word of size word_size=(w,h)
so that:
1) It stays within the black region of the mask.
2) It does not overlap previously placed bounding boxes.
Returns (x, y) or None if no valid position is found.
"""
w, h = word_size
H, W = mask_array.shape
for _ in range(max_attempts):
x = random.randint(0, W - w)
y = random.randint(0, H - h)
# Check if it fits in black region
if not is_region_black(mask_array, x, y, w, h):
continue
# Check collisions with already placed words
candidate_box = (x, y, x + w, y + h)
overlap = any(boxes_overlap(candidate_box, pb) for pb in placed_boxes)
if overlap:
continue
# If we get here, we've found a place
return x, y
return None
# -------------------------------------------------------------------
# Main word cloud creation
# -------------------------------------------------------------------
def generate_masked_wordcloud(
mask_path,
word_freqs,
output_path="masked_wordcloud.png",
font_path="arial.ttf",
base_font_size=60,
min_font_size=12,
width=None,
height=None
):
"""
Generate a word cloud restricted to the black region of a binary mask image.
mask_path : path to a binary silhouette image (black shape on white)
word_freqs: dict of {word: frequency}
output_path: file path to save resulting PNG
font_path: path to a .ttf font file
base_font_size: largest font size to try for the most frequent word
min_font_size: smallest font size before skipping placement
width, height: optional target image size; if None, use mask size
"""
# Load mask image as grayscale
mask_img = Image.open(mask_path).convert("L")
mask_arr = np.array(mask_img)
# If width/height provided, resize mask
if width and height:
mask_img = mask_img.resize((width, height), Image.ANTIALIAS)
mask_arr = np.array(mask_img)
W, H = mask_img.size
# Create drawing canvas
canvas = Image.new("RGB", (W, H), color="white")
draw = ImageDraw.Draw(canvas)
# Sort words by frequency (descending)
words_sorted = sorted(word_freqs.items(), key=lambda x: x[1], reverse=True)
# List of placed bounding boxes
placed_boxes = []
# Range of frequencies
if words_sorted:
max_freq = words_sorted[0][1]
else:
max_freq = 1
for word, freq in words_sorted:
# Scale font size according to frequency
relative_size = freq / max_freq
font_size = int(base_font_size * relative_size)
font_size = max(font_size, min_font_size)
# Try placing smaller if failing
placed = False
cur_size = font_size
while cur_size >= min_font_size and not placed:
font = ImageFont.truetype(font_path, cur_size)
w, h = draw.textsize(word, font=font)
pos = find_position(mask_arr, (w, h), placed_boxes)
if pos:
x, y = pos
# Draw the word in a random color
draw.text((x, y), word, fill=(0,0,0), font=font)
placed_boxes.append((x, y, x + w, y + h))
placed = True
else:
# Try smaller font
cur_size -= 2
if not placed:
print(f"Could not place '{word}' at size >= {min_font_size}.")
canvas.save(output_path)
print(f"Saved word cloud to '{output_path}'.")
# -------------------------------------------------------------------
# Example usage
# -------------------------------------------------------------------
if __name__ == "__main__":
# Example silhouette path (black shape on white background)
MASK_IMAGE_PATH = "silhouette.png"
# Example words/frequencies
word_freqs = {
"Python": 50,
"Cloud": 30,
"Mask": 20,
"Collision": 15,
"Detection": 15,
"Word": 25,
"Image": 10,
"Region": 10,
"Silhouette": 8,
"Pillow": 8,
"Numpy": 8,
"Font": 5,
"Random": 5,
"Placement": 4,
"Black": 4,
"White": 4,
"Data": 3,
"Shape": 3,
"Text": 2,
"Color": 2
}
generate_masked_wordcloud(
mask_path=MASK_IMAGE_PATH,
word_freqs=word_freqs,
output_path="masked_wordcloud.png",
font_path="arial.ttf", # Ensure this font file exists on your system
base_font_size=80,
min_font_size=10
)
How it works
Mask Loading: The mask is read as grayscale. Pixels below a threshold (default 128) are considered “black” (places where text can appear). White areas are blocked.
Placement: Words are sorted by frequency and assigned a font size proportional to that frequency. For each word, the code repeatedly tries random positions on the canvas:
Ensures the candidate bounding box is entirely in the black portion of the mask.
Checks against already placed bounding boxes to prevent overlap.
Collision: If a suitable location is found, the word is drawn; otherwise, the code reduces the font size and tries again until it reaches a minimum size.
Result: A “masked” word cloud appears only within the silhouette region.
You can adapt the word_freqs dictionary, the font file, and the mask image to your needs. A black silhouette on white background is the easiest to work with; if your mask has inverted colors, either invert it or adjust the is_region_black threshold logic accordingly.