Image transformation and codec

Updated at:

This topic describes the operators for image codec, format conversion, size transformation, and pixel processing in the Python DataFrame API.

Before you begin

  • Available only in Realtime Compute Engine VVR 11.8 and later.

  • Encoded image columns use DataType.binary(), and decoded image columns use DataType.image().

  • image_compress and image_convert_format can process encoded images directly. Other operators usually require you to first call image_decode to obtain a DataType.image() column, and then call image_encode as needed to convert the result back to an encoded image.

  • "Input type" and "Return type" use DataFrame API types. Parameter tables use Python types.

Operator overview

Category

Operator

Description

Codec

image_decode

Decode raw image bytes into DataType.image().

image_encode

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

Encoding conversion

image_compress

Recompress encoded image bytes.

image_convert_format

Convert the encoding format.

Type conversion

image_convert_mode

Convert the image mode.

image_to_tensor

Convert an image to a fixed-shape float32 tensor.

Sizing and cropping

image_resize

Resize an image to specified dimensions.

image_rescale

Rescale an image proportionally.

image_crop

Crop an image region.

image_crop_black_border

Detect and crop black borders.

Image enhancement

image_flip

Flip an image.

image_blur

Blur processing.

image_adjust_color

Adjust brightness, contrast, and saturation.

Image background processing

image_remove_background

Remove the image background.

Common runtime parameters

Function signatures retain the runtime parameters that each operator actually supports. To avoid repetition, the operator parameter tables describe only business parameters. Runtime parameters are described below.

Parameter

Type

Default

Applies to

Description

concurrency

Optional[int]

None

All operators on this page

UDF concurrency. None uses the framework default.

model_sharing

Optional[str]

None

image_remove_background

Model sharing mode. None uses the framework default.

batch_size

Optional[int]

None

image_remove_background

Batch size of the Batch UDF. None uses the framework default.

num_gpus

Optional[float]

None

image_remove_background

Number or fraction of GPUs requested per model instance, for example, 1.

gpu_type

Optional[str]

None

image_remove_background

GPU type. Configure this parameter together with num_gpus.

Codec and type conversion

image_decode

Decode raw image bytes into the Flink built-in image type DataType.image().

Input type: DataType.binary(), a column of encoded image bytes.

Function signature:

image_decode(
    *columns,
    on_error="raise",
    mode=None,
    pixel_limit=None,
    concurrency=None
)

Parameter

Type

Default

Description

on_error

str

"raise"

"raise" throws a decoding exception. "null" returns null for inputs that cannot be decoded or that exceed the pixel limit. Note that the Python default differs from the SQL default.

mode

Optional[str]

None

Target image mode. None retains the source mode where possible. If the source mode cannot be represented, the image is converted to RGB or RGBA.

pixel_limit

Optional[int]

None

Maximum number of pixels. Inputs that exceed this limit are handled according to on_error.

Return type: DataType.image().

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

result = df.with_column(
    "image",
    image_decode(
        col("image_bytes"),
        on_error="null",
        mode="RGB",
        pixel_limit=8192 * 8192
    )
)

image_encode

Encode a decoded image into compressed bytes or a Base64 Data URL string.

Input type: DataType.image(), a column of decoded images.

Function signature:

image_encode(
    *columns,
    format=None,
    quality=85,
    output="bytes",
    concurrency=None
)

Parameter

Type

Default

Description

quality

int

85

Encoding quality. Valid values: [1, 100]. This parameter applies only to lossy formats such as JPEG and WebP.

output

str

"bytes"

bytes returns encoded bytes. data_url returns a Base64 Data URL.

format

Optional[str]

None

Target format, for example, "JPEG" or "PNG". Note that None defaults to JPEG. RGBA images are converted to RGB by default when they are encoded as JPEG.

Return type:

  • output="bytes": DataType.binary().

  • output="data_url": DataType.string().

from pyflink.multimodal.operators import image_encode

result = (
    df
    .with_column(
        "jpeg_bytes",
        image_encode(col("image"), format="JPEG", quality=90)
    )
    .with_column(
        "data_url",
        image_encode(col("image"), format="PNG", output="data_url")
    )
)

image_compress

Recompress an encoded image with the specified format and quality factor.

Input type: DataType.binary(), a column of encoded images.

Function signature:

image_compress(
    *columns,
    quality=85,
    format="JPEG",
    concurrency=None
)

Parameter

Type

Default

Description

quality

int

85

Compression quality. Valid values: [1, 100]. This parameter affects lossy formats such as JPEG and WebP.

format

str

"JPEG"

Output format, for example, "JPEG" or "PNG".

Return type: DataType.binary().

from pyflink.multimodal.operators import image_compress

result = df.with_column(
    "compressed",
    image_compress(
        col("image_bytes"),
        quality=60,
        format="JPEG"
    )
)

image_convert_format

Convert an encoded image to a different encoding format.

Input type: DataType.binary(), a column of encoded images.

Function signature:

image_convert_format(
    *columns,
    format,
    concurrency=None
)

Parameter

Type

Default

Description

format

str

Required

Target format, for example, "PNG", "JPEG", "WEBP", or "BMP".

Return type: DataType.binary().

from pyflink.multimodal.operators import image_convert_format

result = df.with_column(
    "png_bytes",
    image_convert_format(
        col("image_bytes"),
        format="PNG"
    )
)

image_convert_mode

Convert an image to the target color mode.

Input type: DataType.image(), a column of decoded images.

Function signature:

image_convert_mode(
    *columns,
    mode,
    concurrency=None
)

Parameter

Type

Default

Description

mode

str

Required

Target mode, for example, RGB, RGBA, L, or L16.

Return type: DataType.image().

from pyflink.multimodal.operators import image_convert_mode

result = df.with_column(
    "grayscale",
    image_convert_mode(
        col("image"),
        mode="L"
    )
)

image_to_tensor

Convert an image to a fixed-shape float32 tensor. This operator does not automatically resize images or convert their modes. It returns None if the dimensions or channel count do not match.

Input type: DataType.image(), a column of decoded images.

Function signature:

image_to_tensor(
    *columns,
    width,
    height,
    mode="RGB",
    layout="CHW",
    concurrency=None
)

Parameter

Type

Default

Description

width

int

Required

The width that input images must have.

height

int

Required

The height that input images must have.

mode

str

"RGB"

Declares the channel count of the output tensor. For example, "RGB" indicates 3 channels and "L" indicates 1 channel. The operator validates only the actual channel count of input images, not the image mode name.

layout

str

"CHW"

"CHW" returns (channels, height, width). "HWC" returns (height, width, channels).

uint8 or uint16 pixels are converted to float32 and scaled to [0, 1].

Return type: DataType.tensor("float32", shape=...). The output shape is determined by width, height, mode, and layout.

from pyflink.multimodal.operators import (
    image_convert_mode,
    image_resize,
    image_to_tensor,
)

result = df.with_column(
    "tensor",
    image_to_tensor(
        col("image"),
        width=224,
        height=224,
        mode="RGB",
        layout="CHW"
    )
)

Sizing and cropping

image_resize

Resize an image to specified dimensions. This scaling is non-proportional. For proportional scaling, use image_rescale.

Input type: DataType.image(), a column of decoded images.

Function signature:

image_resize(
    *columns,
    width,
    height,
    method="lanczos",
    concurrency=None
)

Parameter

Type

Default

Description

width

int

Required

Target width. Must be a positive integer.

height

int

Required

Target height. Must be a positive integer.

method

str

"lanczos"

Resampling method. Supported values: "lanczos", "bilinear", "bicubic", and "nearest".

Return type: DataType.image().

from pyflink.multimodal.operators import image_resize

result = df.with_column(
    "resize_image",
    image_resize(
        col("image"),
        width=256,
        height=256
    )
)

image_rescale

Rescale an image proportionally.

Input type: DataType.image(), a column of decoded images.

Function signature:

image_rescale(
    *columns,
    scale,
    method="lanczos",
    concurrency=None
)

Parameter

Type

Default

Description

scale

float

Required

Scale factor. Must be greater than 0. For example, 0.5 halves the image size.

method

str

"lanczos"

Resampling method. Supported values: "lanczos", "bilinear", "bicubic", and "nearest".

Return type: DataType.image().

from pyflink.multimodal.operators import image_rescale

result = df.with_column(
    "half_size",
    image_rescale(
        col("image"),
        scale=0.5
    )
)

image_crop

Crop an image region.

Input type: DataType.image(), a column of decoded images.

Function signature:

image_crop(
    *columns,
    crop_coords=None,
    crop_type="center",
    crop_ratio=(0.8, 0.8),
    crop_size=None,
    concurrency=None
)

Parameter

Type

Default

Description

crop_coords

Optional[Sequence[int]]

None

Absolute pixel box (x1, y1, x2, y2). When this parameter is set, "coordinate" is used automatically. Regions outside the original image are filled with zero-value pixels.

crop_type

str

"center"

Cropping mode. Supported values: "center", "ratio", and "coordinate".

crop_ratio

Sequence[float]

(0.8, 0.8)

Width and height ratios (width_ratio, height_ratio) to retain. Each value must be in the range (0, 1].

crop_size

Optional[Union[List[int], Tuple[int, int]]]

None

Fixed output (width, height) for center cropping. Used only with "center".

Return type: DataType.image().

from pyflink.multimodal.operators import image_crop

result = df.with_column(
    "roi",
    image_crop(
        col("image"),
        crop_coords=(100, 100, 500, 500)
    )
)

image_crop_black_border

Detect and crop black borders from an image.

Input type: DataType.image(), a column of decoded images.

Function signature:

image_crop_black_border(
    *columns,
    threshold=None,
    detect_algorithm="auto",
    black_threshold=None,
    edge_sensitivity=1.0,
    min_border_size=1,
    concurrency=None
)

Parameter

Type

Default

Description

threshold

Optional[int]

None

A compatibility parameter for black_threshold. This parameter cannot be specified at the same time as black_threshold.

detect_algorithm

str

"auto"

Detection algorithm. Supported values: "auto", "threshold", "histogram", and "edge".

black_threshold

Optional[int]

None

Luminance threshold from 0 to 255. None uses 10. Pixels with luminance at or below this value are treated as black.

edge_sensitivity

float

1.0

Edge detection sensitivity. Valid values: [0.1, 2.0].

min_border_size

int

1

Minimum black border width, in pixels, that triggers cropping.

Return type: DataType.image().

from pyflink.multimodal.operators import image_crop_black_border

result = df.with_column(
    "clean",
    image_crop_black_border(
        col("image"),
        black_threshold=15
    )
)

Image enhancement

image_flip

Flip an image.

Input type: DataType.image(), a column of decoded images.

Function signature:

image_flip(
    *columns,
    mode="horizontal",
    concurrency=None
)

Parameter

Type

Default

Description

mode

str

"horizontal"

Flip direction. Supported values: "horizontal", "vertical", and "rotate180".

Return type: DataType.image().

from pyflink.multimodal.operators import image_flip

result = df.with_column(
    "flipped",
    image_flip(
        col("image"),
        mode="vertical"
    )
)

image_blur

Apply blur processing to an image.

Input type: DataType.image(), a column of decoded images.

Function signature:

image_blur(
    *columns,
    radius=2,
    blur_type="gaussian",
    concurrency=None
)

Parameter

Type

Default

Description

radius

float

2

Blur radius. Must be a finite non-negative number. This parameter does not take effect when blur_type="mean".

blur_type

str

"gaussian"

Blur method. Supported values: "gaussian", "box", and "mean".

Return type: DataType.image().

from pyflink.multimodal.operators import image_blur

result = df.with_column(
    "blurred",
    image_blur(
        col("image"),
        radius=5,
        blur_type="gaussian"
    )
)

image_adjust_color

Adjust brightness, contrast, and saturation.

Input type: DataType.image(), a column of decoded images.

Function signature:

image_adjust_color(
    *columns,
    brightness=1.0,
    contrast=1.0,
    saturation=1.0,
    concurrency=None
)

Parameter

Type

Default

Description

brightness

float

1.0

Brightness factor. Must be non-negative. 1.0 means no change.

contrast

float

1.0

Contrast factor. Must be non-negative. 1.0 means no change.

saturation

float

1.0

Saturation factor. Must be non-negative. 1.0 means no change.

Actual color adjustment is not supported for the L16 mode.

Return type: DataType.image().

from pyflink.multimodal.operators import image_adjust_color

result = df.with_column(
    "enhanced",
    image_adjust_color(
        col("image"),
        brightness=1.1,
        contrast=1.2,
        saturation=0.9
    )
)

image_remove_background

Remove the background of an image and return an image with a transparent background or filled with a specified background color.

Input type: DataType.image(), a column of decoded images.

Dependency: pip install rembg

Function signature:

image_remove_background(
    *columns,
    alpha_matting=False,
    alpha_matting_foreground_threshold=240,
    alpha_matting_background_threshold=10,
    alpha_matting_erode_size=10,
    bgcolor=None,
    model_sharing=None,
    concurrency=None,
    batch_size=None,
    num_gpus=None,
    gpu_type=None
)

Parameter

Type

Default

Description

alpha_matting

bool

False

Whether to enable alpha matting.

alpha_matting_foreground_threshold

int

240

Foreground threshold for alpha matting. Valid values: [0, 255].

alpha_matting_background_threshold

int

10

Background threshold for alpha matting. Valid values: [0, 255].

alpha_matting_erode_size

int

10

Erosion kernel size for alpha matting. Must be a positive integer.

bgcolor

Optional[Union[List[int], Tuple[int, int, int, int]]]

None

RGBA background color (R, G, B, A). The list must contain exactly 4 elements, and each element must be in the range [0, 255]. None uses a transparent background.

Return type: DataType.image().

from pyflink.multimodal.operators import image_remove_background

result = df.with_column(
    "foreground",
    image_remove_background(
        col("image"),
        alpha_matting=True,
        bgcolor=(255, 255, 255, 255)
    )
)