Image operator overview

Updated at:

The Python DataFrame API provides operators for image validation, encoding and decoding, transformation, filtering, detection, quality scoring, and more. This topic describes the invocation methods, data types, error handling, and runtime parameters of image operators.

Limits

Available only in Realtime Compute Engine VVR 11.8 and later.

Usage

Usage notes

When you develop Python jobs based on the DataFrame API, import all image operators from pyflink.multimodal.operators. The image processing dependencies are built in, so you do not need to add extra dependencies to your job.

from pyflink.dataframe import col
from pyflink.multimodal.operators import image_metadata, image_decode

result = df.with_column(
    "metadata",
    image_metadata(col("image")),
)

Invocation methods

You can pass input columns to an operator and configure parameters in the same call. Parameters must be specified as keyword arguments.

from pyflink.dataframe import col
from pyflink.multimodal.operators import image_resize

result = df.with_column(
    "resized",
    image_resize(
        col("image"),
        width=512,
        height=512,
        method="lanczos"
    )
)

Alternatively, you can create a configured operator first and then apply it to one or more columns:

resize = image_resize(
    width=512,
    height=512,
    method="lanczos",
)

result = df.with_column(
    "resized",
    resize(col("image")),
)

Operator overview

Category

Operator

Description

Encoding and decoding

image_decode

Decodes raw image bytes into DataType.image().

image_encode

Encodes a decoded image into compressed bytes or a Data URL.

Encoding conversion

image_compress

Recompresses encoded image bytes.

image_convert_format

Converts the encoding format.

Type conversion

image_convert_mode

Converts the image mode.

image_to_tensor

Converts an image to a fixed-shape float32 tensor.

Sizing and cropping

image_resize

Resizes an image to specified dimensions.

image_rescale

Rescales an image proportionally.

image_crop

Crops an image region.

image_crop_black_border

Detects and crops black borders.

Image enhancement

image_flip

Flips an image.

image_blur

Blurs an image.

image_adjust_color

Adjusts brightness, contrast, and saturation.

Background processing

image_remove_background

Removes the image background.

Validity check

is_valid_image

Checks whether an image passes the validity check.

Attribute extraction

image_metadata

Extracts the width, height, number of channels, mode, and other attributes of an image.

image_aspect_ratio

Computes the aspect ratio.

image_sharpness

Computes image sharpness by using the Laplacian variance.

image_hash

Computes the perceptual hash (phash) of an image.

Data filtering

image_size_filter

Filters images by pixel dimensions.

image_shape_filter

Filters images by aspect ratio.

image_file_size_filter

Filters images by file size.

Detection and recognition

image_detect_objects

Detects objects by using YOLO.

image_segment

Generates segmentation masks for images by using FastSAM.

image_ocr

Extracts text from images by using EasyOCR.

image_detect_subplot

Determines whether an image is a collage and returns the number of sub-images.

Face processing

image_face_detect

Detects faces and returns bounding boxes.

image_face_count

Counts the number of faces in an image.

image_face_blur

Blurs face regions.

Embedding and similarity

image_embedding

Generates CLIP embedding vectors from images.

image_text_similarity

Computes the CLIP cosine similarity between images and text.

Quality scoring

image_quality_score

Computes a composite quality score.

image_nsfw_score

Assesses the risk of NSFW content.

image_aesthetic_score

Assesses the aesthetic quality of images.

image_watermark_score

Assesses the risk that an image contains a watermark.

Data type description

Image data forms

Data form

DataFrame type

Description

Encoded image

DataType.binary()

Image file bytes in formats such as JPEG, PNG, and WebP.

Decoded image

DataType.image()

A built-in type that represents a decoded image. Used as the input or output of most built-in image operators.

Image tensor

DataType.tensor(...)

A built-in type. The fixed-shape float32 tensor returned by image_to_tensor is commonly used as input for model inference.

Data URL

DataType.string()

image_encode(output="data_url") returns a base64-encoded image string.

  • Different operators accept different data forms. Refer to the parameter table of each operator.

  • Most image processing operators take DataType.image as input. If the data source contains encoded image bytes, call image_decode first to decode them. Only a few operators support DataType.binary or both input types.

  • Image encoding operators typically support the following formats: JPEG, PNG, TIFF, WEBP, BMP, GIF.

Built-in IMAGE type

DataType.image represents a decoded image. It contains pixel data along with three metadata fields: width, height, and image mode. The original encoding format of the file, such as JPEG or PNG, is not retained.

The following operators convert between encoded bytes and IMAGE:

  • image_decode: decodes an encoded image (DataType.binary) into DataType.image.

  • image_encode: encodes DataType.image into image bytes (DataType.binary) or a Data URL (DataType.string).

Image preview

Preview decoded images

After you encode DataType.image into a Data URL, you can use the result as an image URL in a browser.

from pyflink.multimodal.operators import image_encode

result = df.with_column(
    "preview_url",
    image_encode(
        col("image"),
        format="JPEG",
        quality=85,
        output="data_url"  # Select data_url.
    )
)

The return value is in the following format:

data:image/jpeg;base64,...

Preview encoded images

An encoded image (DataType.binary) can be used as an image URL in a browser only after it is converted into a Base64 Data URL with the correct MIME type. Currently, call image_decode first, and then call image_encode.

Null and error handling

Scenario

Configuration

Raise an exception when image bytes cannot be decoded or exceed the pixel limit

image_decode(on_error="raise") (default behavior of Python operators)

Return a null value when image bytes cannot be decoded or exceed the pixel limit

image_decode(on_error="null")

Lightweight check of image validity

is_valid_image(...)

Note: is_valid_image only checks whether the container header and basic attributes are valid. It does not guarantee that the full image can be decoded.

Runtime parameters of model-based operators

Operators support the following Python runtime parameters. Different operators support different parameter combinations. For usage details, see the section of each operator.

Parameter

Type

Description

batch_size

Optional[int]

The Arrow batch size of the Pandas UDF. None uses the framework default.

model_sharing

Optional[str]

The sharing mode of local model weights. Two modes are supported: process and shared.

num_gpus

Optional[float]

The number of GPUs requested for an operator slot.

gpu_type

Optional[str]

The GPU type label, for example, A10. The actual value depends on the GPU specification that you use.

concurrency

Optional[int]

The UDF concurrency. None uses the framework default.

Pipeline example

The following example decodes images, filters out data that fails to decode, unifies image sizes, and generates image metadata and encoded bytes.

from pyflink.dataframe import col
from pyflink.multimodal.operators import (
    image_decode,
    image_encode,
    image_metadata,
    image_resize,
)

decoded = (
    df.with_column(
        "image",
        image_decode(
            col("image_bytes"),
            on_error="null",
            mode="RGB",
            concurrency=5
        )
    )
    .filter(col("image").is_not_null)
)

resized = decoded.with_column(
    "image_512",
    image_resize(
        col("image"),
        width=512,
        height=512,
        method="lanczos"
    )
)

result = (
    resized
    .with_column(
        "metadata",
        image_metadata(col("image_512")),
    )
    .with_column(
        "resized_image_bytes",
        image_encode(
            col("image_512"),
            format="JPEG",
            quality=85
        )
    )
)

References