Skip to content

colorize_img()

Colorizes black and white images or re-colors existing images. Optionally adds a caption.

Parameters:

Name Type Description Default
img Image

The image to be colorized.

required
max_width int

The maximum width of the output image, defaults to 1024.

1024
max_height int

The maximum height of the output image, defaults to 1024.

1024
caption str

A caption for the image. If None, a caption is generated and modified.

None

Returns:

Name Type Description
Image

The colorized version of the input image.

Source code in imaginairy/api/colorize.py
def colorize_img(img, max_width=1024, max_height=1024, caption=None):
    """
    Colorizes black and white images or re-colors existing images. Optionally adds a caption.

    Args:
        img (Image): The image to be colorized.
        max_width (int, optional): The maximum width of the output image, defaults to 1024.
        max_height (int, optional): The maximum height of the output image, defaults to 1024.
        caption (str, optional): A caption for the image. If None, a caption is generated and modified.

    Returns:
        Image: The colorized version of the input image.

    """
    if not caption:
        caption = generate_caption(img, min_length=10)
        caption = caption.replace("black and white", "color")
        caption = caption.replace("old picture", "professional color photo")
        caption = caption.replace("vintage photograph", "professional color photo")
        caption = caption.replace("old photo", "professional color photo")
        caption = caption.replace("vintage photo", "professional color photo")
        caption = caption.replace("old color", "color")
        caption = caption.replace(" old fashioned ", " ")
        caption = caption.replace(" old time ", " ")
        caption = caption.replace(" old ", " ")
        logger.info(caption)
    control_inputs = [
        ControlInput(mode="colorize", image=img, strength=2),
    ]
    prompt_add = ". color photo, sharp-focus, highly detailed, intricate, Canon 5D"
    prompt = ImaginePrompt(
        prompt=f"{caption}{prompt_add}",
        init_image=img,
        init_image_strength=0.0,
        control_inputs=control_inputs,
        size=(min(img.width, max_width), min(img.height, max_height)),
        steps=30,
        prompt_strength=12,
    )
    result = next(iter(imagine(prompt)))
    colorized_img = replace_color(img, result.images["generated"])

    # allows the algorithm some leeway for the overall brightness of the image
    # results look better with this
    colorized_img = match_brightness(colorized_img, result.images["generated"])

    return colorized_img