Initial commit: new baseline
This commit is contained in:
@@ -0,0 +1,272 @@
|
||||
"""Functional implementations for text manipulation and rendering.
|
||||
|
||||
This module provides utility functions for manipulating text in strings and
|
||||
rendering text onto images. Includes functions for word manipulation, text drawing,
|
||||
and handling text regions in images.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
from albucore import (
|
||||
MONO_CHANNEL_DIMENSIONS,
|
||||
NUM_MULTI_CHANNEL_DIMENSIONS,
|
||||
NUM_RGB_CHANNELS,
|
||||
preserve_channel_dim,
|
||||
uint8_io,
|
||||
)
|
||||
|
||||
from albumentations.core.type_definitions import PAIR
|
||||
|
||||
# Importing wordnet and other dependencies only for type checking
|
||||
if TYPE_CHECKING:
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def delete_random_words(words: list[str], num_words: int, py_random: random.Random) -> str:
|
||||
"""Delete a specified number of random words from a list.
|
||||
|
||||
This function randomly removes words from the input list and joins the remaining
|
||||
words with spaces to form a new string.
|
||||
|
||||
Args:
|
||||
words (list[str]): List of words to process.
|
||||
num_words (int): Number of words to delete.
|
||||
py_random (random.Random): Random number generator for reproducibility.
|
||||
|
||||
Returns:
|
||||
str: New string with specified words removed. Returns empty string if
|
||||
num_words is greater than or equal to the length of words.
|
||||
|
||||
"""
|
||||
if num_words >= len(words):
|
||||
return ""
|
||||
|
||||
indices_to_delete = py_random.sample(range(len(words)), num_words)
|
||||
new_words = [word for idx, word in enumerate(words) if idx not in indices_to_delete]
|
||||
return " ".join(new_words)
|
||||
|
||||
|
||||
def swap_random_words(words: list[str], num_words: int, py_random: random.Random) -> str:
|
||||
"""Swap random pairs of words in a list of words.
|
||||
|
||||
This function randomly selects pairs of words and swaps their positions
|
||||
a specified number of times.
|
||||
|
||||
Args:
|
||||
words (list[str]): List of words to process.
|
||||
num_words (int): Number of swaps to perform.
|
||||
py_random (random.Random): Random number generator for reproducibility.
|
||||
|
||||
Returns:
|
||||
str: New string with words swapped. If num_words is 0 or the list has fewer
|
||||
than 2 words, returns the original string.
|
||||
|
||||
"""
|
||||
if num_words == 0 or len(words) < PAIR:
|
||||
return " ".join(words)
|
||||
|
||||
words = words.copy()
|
||||
|
||||
for _ in range(num_words):
|
||||
idx1, idx2 = py_random.sample(range(len(words)), 2)
|
||||
words[idx1], words[idx2] = words[idx2], words[idx1]
|
||||
return " ".join(words)
|
||||
|
||||
|
||||
def insert_random_stopwords(
|
||||
words: list[str],
|
||||
num_insertions: int,
|
||||
stopwords: tuple[str, ...] | None,
|
||||
py_random: random.Random,
|
||||
) -> str:
|
||||
"""Insert random stopwords into a list of words.
|
||||
|
||||
This function randomly inserts stopwords at random positions in the
|
||||
list of words a specified number of times.
|
||||
|
||||
Args:
|
||||
words (list[str]): List of words to process.
|
||||
num_insertions (int): Number of stopwords to insert.
|
||||
stopwords (tuple[str, ...] | None): Tuple of stopwords to choose from.
|
||||
If None, default stopwords will be used.
|
||||
py_random (random.Random): Random number generator for reproducibility.
|
||||
|
||||
Returns:
|
||||
str: New string with stopwords inserted.
|
||||
|
||||
"""
|
||||
if stopwords is None:
|
||||
stopwords = ("and", "the", "is", "in", "at", "of") # Default stopwords if none provided
|
||||
|
||||
for _ in range(num_insertions):
|
||||
idx = py_random.randint(0, len(words))
|
||||
words.insert(idx, py_random.choice(stopwords))
|
||||
return " ".join(words)
|
||||
|
||||
|
||||
def convert_image_to_pil(image: np.ndarray) -> Image:
|
||||
"""Convert a NumPy array image to a PIL image."""
|
||||
try:
|
||||
from PIL import Image
|
||||
except ImportError:
|
||||
raise ImportError("Pillow is not installed") from ImportError
|
||||
|
||||
if image.ndim == MONO_CHANNEL_DIMENSIONS: # (height, width)
|
||||
return Image.fromarray(image)
|
||||
if image.ndim == NUM_MULTI_CHANNEL_DIMENSIONS and image.shape[2] == 1: # (height, width, 1)
|
||||
return Image.fromarray(image[:, :, 0], mode="L")
|
||||
if image.ndim == NUM_MULTI_CHANNEL_DIMENSIONS and image.shape[2] == NUM_RGB_CHANNELS: # (height, width, 3)
|
||||
return Image.fromarray(image)
|
||||
|
||||
raise TypeError(f"Unsupported image shape: {image.shape}")
|
||||
|
||||
|
||||
def draw_text_on_pil_image(pil_image: Image, metadata_list: list[dict[str, Any]]) -> Image:
|
||||
"""Draw text on a PIL image."""
|
||||
try:
|
||||
from PIL import ImageDraw
|
||||
except ImportError:
|
||||
raise ImportError("Pillow is not installed") from ImportError
|
||||
|
||||
draw = ImageDraw.Draw(pil_image)
|
||||
for metadata in metadata_list:
|
||||
bbox_coords = metadata["bbox_coords"]
|
||||
text = metadata["text"]
|
||||
font = metadata["font"]
|
||||
font_color = metadata["font_color"]
|
||||
|
||||
# Adapt font_color based on image mode
|
||||
if pil_image.mode == "L": # Grayscale
|
||||
# For grayscale images, use only the first value or average the RGB values
|
||||
if isinstance(font_color, tuple):
|
||||
if len(font_color) >= 3:
|
||||
# Average RGB values for grayscale
|
||||
font_color = int(sum(font_color[:3]) / 3)
|
||||
elif len(font_color) == 1:
|
||||
font_color = int(font_color[0])
|
||||
# For RGB and other modes, ensure font_color is a tuple of integers
|
||||
elif isinstance(font_color, tuple):
|
||||
font_color = tuple(int(c) for c in font_color)
|
||||
|
||||
position = bbox_coords[:2]
|
||||
draw.text(position, text, font=font, fill=font_color)
|
||||
return pil_image
|
||||
|
||||
|
||||
def draw_text_on_multi_channel_image(image: np.ndarray, metadata_list: list[dict[str, Any]]) -> np.ndarray:
|
||||
"""Draw text on a multi-channel image with more than three channels."""
|
||||
try:
|
||||
from PIL import Image, ImageDraw
|
||||
except ImportError:
|
||||
raise ImportError("Pillow is not installed") from ImportError
|
||||
|
||||
channels = [Image.fromarray(image[:, :, i]) for i in range(image.shape[2])]
|
||||
pil_images = [ImageDraw.Draw(channel) for channel in channels]
|
||||
|
||||
for metadata in metadata_list:
|
||||
bbox_coords = metadata["bbox_coords"]
|
||||
text = metadata["text"]
|
||||
font = metadata["font"]
|
||||
font_color = metadata["font_color"]
|
||||
|
||||
# Handle font_color as tuple[float, ...]
|
||||
# Ensure we have enough color values for all channels
|
||||
if len(font_color) < image.shape[2]:
|
||||
# If fewer values than channels, pad with zeros
|
||||
font_color = tuple(list(font_color) + [0] * (image.shape[2] - len(font_color)))
|
||||
elif len(font_color) > image.shape[2]:
|
||||
# If more values than channels, truncate
|
||||
font_color = font_color[: image.shape[2]]
|
||||
|
||||
# Convert to integers for PIL
|
||||
font_color = [int(c) for c in font_color]
|
||||
|
||||
position = bbox_coords[:2]
|
||||
|
||||
# For each channel, use the corresponding color value
|
||||
for channel_id, pil_image in enumerate(pil_images):
|
||||
# For single-channel PIL images, color must be an integer
|
||||
pil_image.text(position, text, font=font, fill=font_color[channel_id])
|
||||
|
||||
return np.stack([np.array(channel) for channel in channels], axis=2)
|
||||
|
||||
|
||||
@uint8_io
|
||||
@preserve_channel_dim
|
||||
def render_text(image: np.ndarray, metadata_list: list[dict[str, Any]], clear_bg: bool) -> np.ndarray:
|
||||
"""Render text onto an image based on provided metadata.
|
||||
|
||||
This function draws text on an image using metadata that specifies text content,
|
||||
position, font, and color. It can optionally clear the background before rendering.
|
||||
The function handles different image types (grayscale, RGB, multi-channel).
|
||||
|
||||
Args:
|
||||
image (np.ndarray): Image to draw text on.
|
||||
metadata_list (list[dict[str, Any]]): List of metadata dictionaries containing:
|
||||
- bbox_coords: Bounding box coordinates (x_min, y_min, x_max, y_max)
|
||||
- text: Text string to render
|
||||
- font: PIL ImageFont object
|
||||
- font_color: Color for the text
|
||||
clear_bg (bool): Whether to clear (inpaint) the background under the text.
|
||||
|
||||
Returns:
|
||||
np.ndarray: Image with text rendered on it.
|
||||
|
||||
"""
|
||||
# First clean background under boxes using seamless clone if clear_bg is True
|
||||
if clear_bg:
|
||||
image = inpaint_text_background(image, metadata_list)
|
||||
|
||||
if len(image.shape) == MONO_CHANNEL_DIMENSIONS or (
|
||||
len(image.shape) == NUM_MULTI_CHANNEL_DIMENSIONS and image.shape[2] in {1, NUM_RGB_CHANNELS}
|
||||
):
|
||||
pil_image = convert_image_to_pil(image)
|
||||
pil_image = draw_text_on_pil_image(pil_image, metadata_list)
|
||||
return np.array(pil_image)
|
||||
|
||||
return draw_text_on_multi_channel_image(image, metadata_list)
|
||||
|
||||
|
||||
def inpaint_text_background(
|
||||
image: np.ndarray,
|
||||
metadata_list: list[dict[str, Any]],
|
||||
method: int = cv2.INPAINT_TELEA,
|
||||
) -> np.ndarray:
|
||||
"""Inpaint (clear) regions in an image where text will be rendered.
|
||||
|
||||
This function creates a clean background for text by inpainting rectangular
|
||||
regions specified in the metadata. It removes any existing content in those
|
||||
regions to provide a clean slate for rendering text.
|
||||
|
||||
Args:
|
||||
image (np.ndarray): Image to inpaint.
|
||||
metadata_list (list[dict[str, Any]]): List of metadata dictionaries containing:
|
||||
- bbox_coords: Bounding box coordinates (x_min, y_min, x_max, y_max)
|
||||
method (int, optional): Inpainting method to use. Defaults to cv2.INPAINT_TELEA.
|
||||
Options include:
|
||||
- cv2.INPAINT_TELEA: Fast Marching Method
|
||||
- cv2.INPAINT_NS: Navier-Stokes method
|
||||
|
||||
Returns:
|
||||
np.ndarray: Image with specified regions inpainted.
|
||||
|
||||
"""
|
||||
result_image = image.copy()
|
||||
mask = np.zeros((image.shape[0], image.shape[1]), dtype=np.uint8)
|
||||
|
||||
for metadata in metadata_list:
|
||||
x_min, y_min, x_max, y_max = metadata["bbox_coords"]
|
||||
|
||||
# Black out the region
|
||||
result_image[y_min:y_max, x_min:x_max] = 0
|
||||
|
||||
# Update the mask to indicate the region to inpaint
|
||||
mask[y_min:y_max, x_min:x_max] = 255
|
||||
|
||||
# Inpaint the blacked-out regions
|
||||
return cv2.inpaint(result_image, mask, inpaintRadius=3, flags=method)
|
||||
@@ -0,0 +1,299 @@
|
||||
"""Transforms for text rendering and augmentation on images.
|
||||
|
||||
This module provides transforms for adding and manipulating text on images,
|
||||
including text augmentation techniques like word insertion, deletion, and swapping.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal
|
||||
|
||||
import numpy as np
|
||||
from pydantic import AfterValidator
|
||||
|
||||
import albumentations.augmentations.text.functional as ftext
|
||||
from albumentations.core.bbox_utils import check_bboxes, denormalize_bboxes
|
||||
from albumentations.core.pydantic import check_range_bounds, nondecreasing
|
||||
from albumentations.core.transforms_interface import BaseTransformInitSchema, ImageOnlyTransform
|
||||
|
||||
__all__ = ["TextImage"]
|
||||
|
||||
|
||||
class TextImage(ImageOnlyTransform):
|
||||
"""Apply text rendering transformations on images.
|
||||
|
||||
This class supports rendering text directly onto images using a variety of configurations,
|
||||
such as custom fonts, font sizes, colors, and augmentation methods. The text can be placed
|
||||
inside specified bounding boxes.
|
||||
|
||||
Args:
|
||||
font_path (str | Path): Path to the font file to use for rendering text.
|
||||
stopwords (list[str] | None): List of stopwords for text augmentation.
|
||||
augmentations (tuple[str | None, ...]): List of text augmentations to apply.
|
||||
None: text is printed as is
|
||||
"insertion": insert random stop words into the text.
|
||||
"swap": swap random words in the text.
|
||||
"deletion": delete random words from the text.
|
||||
fraction_range (tuple[float, float]): Range for selecting a fraction of bounding boxes to modify.
|
||||
font_size_fraction_range (tuple[float, float]): Range for selecting the font size as a fraction of
|
||||
bounding box height.
|
||||
font_color (tuple[float, ...]): Font color as RGB values (e.g., (0, 0, 0) for black).
|
||||
clear_bg (bool): Whether to clear the background before rendering text.
|
||||
metadata_key (str): Key to access metadata in the parameters.
|
||||
p (float): Probability of applying the transform.
|
||||
|
||||
Targets:
|
||||
image, volume
|
||||
|
||||
Image types:
|
||||
uint8, float32
|
||||
|
||||
References:
|
||||
doc-augmentation: https://github.com/danaaubakirova/doc-augmentation
|
||||
|
||||
Examples:
|
||||
>>> import albumentations as A
|
||||
>>> transform = A.Compose([
|
||||
A.TextImage(
|
||||
font_path=Path("/path/to/font.ttf"),
|
||||
stopwords=("the", "is", "in"),
|
||||
augmentations=("insertion", "deletion"),
|
||||
fraction_range=(0.5, 1.0),
|
||||
font_size_fraction_range=(0.5, 0.9),
|
||||
font_color=(255, 0, 0), # red in RGB
|
||||
metadata_key="text_metadata",
|
||||
p=0.5
|
||||
)
|
||||
])
|
||||
>>> transformed = transform(image=my_image, text_metadata=my_metadata)
|
||||
>>> image = transformed['image']
|
||||
# This will render text on `my_image` based on the metadata provided in `my_metadata`.
|
||||
|
||||
"""
|
||||
|
||||
class InitSchema(BaseTransformInitSchema):
|
||||
font_path: str | Path
|
||||
stopwords: tuple[str, ...]
|
||||
augmentations: tuple[str | None, ...]
|
||||
fraction_range: Annotated[
|
||||
tuple[float, float],
|
||||
AfterValidator(nondecreasing),
|
||||
AfterValidator(check_range_bounds(0, 1)),
|
||||
]
|
||||
font_size_fraction_range: Annotated[
|
||||
tuple[float, float],
|
||||
AfterValidator(nondecreasing),
|
||||
AfterValidator(check_range_bounds(0, 1)),
|
||||
]
|
||||
font_color: tuple[float, ...]
|
||||
clear_bg: bool
|
||||
metadata_key: str
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
font_path: str | Path,
|
||||
stopwords: tuple[str, ...] = ("the", "is", "in", "at", "of"),
|
||||
augmentations: tuple[Literal["insertion", "swap", "deletion"] | None, ...] = (None,),
|
||||
fraction_range: tuple[float, float] = (1.0, 1.0),
|
||||
font_size_fraction_range: tuple[float, float] = (0.8, 0.9),
|
||||
font_color: tuple[float, ...] = (0, 0, 0), # black in RGB
|
||||
clear_bg: bool = False,
|
||||
metadata_key: str = "textimage_metadata",
|
||||
p: float = 0.5,
|
||||
) -> None:
|
||||
super().__init__(p=p)
|
||||
self.metadata_key = metadata_key
|
||||
self.font_path = font_path
|
||||
self.fraction_range = fraction_range
|
||||
self.stopwords = stopwords
|
||||
self.augmentations = list(augmentations)
|
||||
self.font_size_fraction_range = font_size_fraction_range
|
||||
self.font_color = font_color
|
||||
self.clear_bg = clear_bg
|
||||
|
||||
@property
|
||||
def targets_as_params(self) -> list[str]:
|
||||
"""Get list of targets that should be passed as parameters to transforms.
|
||||
|
||||
Returns:
|
||||
list[str]: List containing the metadata key name
|
||||
|
||||
"""
|
||||
return [self.metadata_key]
|
||||
|
||||
def random_aug(
|
||||
self,
|
||||
text: str,
|
||||
fraction: float,
|
||||
choice: Literal["insertion", "swap", "deletion"],
|
||||
) -> str:
|
||||
"""Apply a random text augmentation to the input text.
|
||||
|
||||
Args:
|
||||
text (str): Original text to augment
|
||||
fraction (float): Fraction of words to modify
|
||||
choice (Literal["insertion", "swap", "deletion"]): Type of augmentation to apply
|
||||
|
||||
Returns:
|
||||
str: Augmented text or empty string if no change was made
|
||||
|
||||
Raises:
|
||||
ValueError: If an invalid choice is provided
|
||||
|
||||
"""
|
||||
words = [word for word in text.strip().split() if word]
|
||||
num_words = len(words)
|
||||
num_words_to_modify = max(1, int(fraction * num_words))
|
||||
|
||||
if choice == "insertion":
|
||||
result_sentence = ftext.insert_random_stopwords(words, num_words_to_modify, self.stopwords, self.py_random)
|
||||
elif choice == "swap":
|
||||
result_sentence = ftext.swap_random_words(words, num_words_to_modify, self.py_random)
|
||||
elif choice == "deletion":
|
||||
result_sentence = ftext.delete_random_words(words, num_words_to_modify, self.py_random)
|
||||
else:
|
||||
raise ValueError("Invalid choice. Choose from 'insertion', 'swap', or 'deletion'.")
|
||||
|
||||
result_sentence = re.sub(" +", " ", result_sentence).strip()
|
||||
return result_sentence if result_sentence != text else ""
|
||||
|
||||
def preprocess_metadata(
|
||||
self,
|
||||
image: np.ndarray,
|
||||
bbox: tuple[float, float, float, float],
|
||||
text: str,
|
||||
bbox_index: int,
|
||||
) -> dict[str, Any]:
|
||||
"""Preprocess text metadata for a single bounding box.
|
||||
|
||||
Args:
|
||||
image (np.ndarray): Input image
|
||||
bbox (tuple[float, float, float, float]): Normalized bounding box coordinates
|
||||
text (str): Text to render in the bounding box
|
||||
bbox_index (int): Index of the bounding box in the original metadata
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: Processed metadata including font, position, and text information
|
||||
|
||||
Raises:
|
||||
ImportError: If PIL.ImageFont is not installed
|
||||
|
||||
"""
|
||||
try:
|
||||
from PIL import ImageFont
|
||||
except ImportError as err:
|
||||
raise ImportError(
|
||||
"ImageFont from PIL is required to use TextImage transform. Install it with `pip install Pillow`.",
|
||||
) from err
|
||||
check_bboxes(np.array([bbox]))
|
||||
denormalized_bbox = denormalize_bboxes(np.array([bbox]), image.shape[:2])[0]
|
||||
|
||||
x_min, y_min, x_max, y_max = (int(x) for x in denormalized_bbox[:4])
|
||||
bbox_height = y_max - y_min
|
||||
|
||||
font_size_fraction = self.py_random.uniform(*self.font_size_fraction_range)
|
||||
|
||||
font = ImageFont.truetype(str(self.font_path), int(font_size_fraction * bbox_height))
|
||||
|
||||
if not self.augmentations or self.augmentations is None:
|
||||
augmented_text = text
|
||||
else:
|
||||
augmentation = self.py_random.choice(self.augmentations)
|
||||
|
||||
augmented_text = text if augmentation is None else self.random_aug(text, 0.5, choice=augmentation)
|
||||
|
||||
font_color = self.font_color
|
||||
|
||||
return {
|
||||
"bbox_coords": (x_min, y_min, x_max, y_max),
|
||||
"bbox_index": bbox_index,
|
||||
"original_text": text,
|
||||
"text": augmented_text,
|
||||
"font": font,
|
||||
"font_color": font_color,
|
||||
}
|
||||
|
||||
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Generate parameters based on input data.
|
||||
|
||||
Args:
|
||||
params (dict[str, Any]): Dictionary of existing parameters
|
||||
data (dict[str, Any]): Dictionary containing input data with image and metadata
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: Dictionary containing the overlay data for text rendering
|
||||
|
||||
"""
|
||||
image = data["image"] if "image" in data else data["images"][0]
|
||||
|
||||
metadata = data[self.metadata_key]
|
||||
|
||||
if metadata == []:
|
||||
return {
|
||||
"overlay_data": [],
|
||||
}
|
||||
|
||||
if isinstance(metadata, dict):
|
||||
metadata = [metadata]
|
||||
|
||||
fraction = self.py_random.uniform(*self.fraction_range)
|
||||
|
||||
num_bboxes_to_modify = int(len(metadata) * fraction)
|
||||
|
||||
bbox_indices_to_update = self.py_random.sample(range(len(metadata)), num_bboxes_to_modify)
|
||||
|
||||
overlay_data = [
|
||||
self.preprocess_metadata(image, metadata[bbox_index]["bbox"], metadata[bbox_index]["text"], bbox_index)
|
||||
for bbox_index in bbox_indices_to_update
|
||||
]
|
||||
|
||||
return {
|
||||
"overlay_data": overlay_data,
|
||||
}
|
||||
|
||||
def apply(
|
||||
self,
|
||||
img: np.ndarray,
|
||||
overlay_data: list[dict[str, Any]],
|
||||
**params: Any,
|
||||
) -> np.ndarray:
|
||||
"""Apply text rendering to the input image.
|
||||
|
||||
Args:
|
||||
img (np.ndarray): Input image
|
||||
overlay_data (list[dict[str, Any]]): List of dictionaries containing text rendering information
|
||||
**params (Any): Additional parameters
|
||||
|
||||
Returns:
|
||||
np.ndarray: Image with rendered text
|
||||
|
||||
"""
|
||||
return ftext.render_text(img, overlay_data, clear_bg=self.clear_bg)
|
||||
|
||||
def apply_with_params(self, params: dict[str, Any], *args: Any, **kwargs: Any) -> dict[str, Any]:
|
||||
"""Apply the transform and include overlay data in the result.
|
||||
|
||||
Args:
|
||||
params (dict[str, Any]): Parameters for the transform
|
||||
*args (Any): Additional positional arguments
|
||||
**kwargs (Any): Additional keyword arguments
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: Dictionary containing the transformed data and simplified overlay information
|
||||
|
||||
"""
|
||||
res = super().apply_with_params(params, *args, **kwargs)
|
||||
res["overlay_data"] = [
|
||||
{
|
||||
"bbox_coords": overlay["bbox_coords"],
|
||||
"text": overlay["text"],
|
||||
"original_text": overlay["original_text"],
|
||||
"bbox_index": overlay["bbox_index"],
|
||||
"font_color": overlay["font_color"],
|
||||
}
|
||||
for overlay in params["overlay_data"]
|
||||
]
|
||||
|
||||
return res
|
||||
Reference in New Issue
Block a user