Image detection and face processing

Updated at:

This topic describes the operators for object detection, image segmentation, text recognition, subplot detection, and face processing in the Python DataFrame API.

Before you begin

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

  • Model-based operators can run on CPUs or GPUs. The device is selected automatically based on whether GPU resources are configured.

Operator list

Category

Operator

Description

Detection and recognition

image_detect_objects

Detect objects using YOLO.

image_segment

Generate image segmentation masks using FastSAM.

image_ocr

Extract text from images using EasyOCR.

image_detect_subplot

Determine whether an image is a collage and return the number of sub-images.

Face processing

image_face_detect

Detect faces and return bounding boxes.

image_face_count

Count the number of faces in an image.

image_face_blur

Blur face regions.

Common runtime parameters

Function signatures retain the runtime parameters that each operator actually supports. To avoid repetition, operator parameter tables describe only business parameters. Runtime parameters are described below. The model-based operators on this page include image_detect_objects, image_segment, and image_ocr.

Parameter

Type

Default

Description

concurrency

Optional[int]

None

UDF concurrency. None uses the framework default.

model_sharing

Optional[str]

None

Model sharing mode. None uses the framework default.

batch_size

Optional[int]

None

Batch size for the batch UDF. None uses the framework default.

num_gpus

Optional[float]

None

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

gpu_type

Optional[str]

None

GPU type. Set together with num_gpus.

Detection and recognition

image_detect_objects

Dependency: pip install ultralytics

Detect objects using YOLO.

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

Signature:

image_detect_objects(
    *columns,
    model="yolov8n",
    confidence=0.05,
    imgsz=640,
    iou=0.5,
    model_sharing=None,
    concurrency=None,
    batch_size=None,
    num_gpus=None,
    gpu_type=None
)

Parameter

Type

Default

Description

model

str

"yolov8n"

YOLO model name or path. Only the yolov8n model is currently built in.

confidence

float

0.05

Minimum detection confidence, range [0, 1].

imgsz

int

640

Inference resolution. Must be a positive integer.

iou

float

0.5

NMS IoU threshold, range [0, 1].

Return type:

DataType.list(
    DataType.struct({
        "label": DataType.string(),
        "x": DataType.float64(),
        "y": DataType.float64(),
        "w": DataType.float64(),
        "h": DataType.float64(),
        "confidence": DataType.float64()
    })
)

x and y are the coordinates of the top-left corner of the bounding box. w and h are the width and height of the bounding box.

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

result = df.with_column(
    "objects",
    image_detect_objects(
        col("image"),
        model="yolov8n",
        confidence=0.25
    )
)

image_segment

Dependency: pip install ultralytics

Generate image segmentation masks using FastSAM.

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

Signature:

image_segment(
    *columns,
    model="FastSAM-x.pt",
    confidence=0.05,
    imgsz=1024,
    iou=0.5,
    model_sharing=None,
    concurrency=None,
    batch_size=None,
    num_gpus=None,
    gpu_type=None
)

Parameter

Type

Default

Description

model

str

"FastSAM-x.pt"

FastSAM model name or path. Only the FastSAM-x.pt model is currently built in.

confidence

float

0.05

Minimum confidence, range [0, 1].

imgsz

int

1024

Inference resolution. Must be a positive integer.

iou

float

0.5

NMS IoU threshold, range [0, 1].

Return type: DataType.binary(), a PNG-encoded region map.

In the region map:

  • Pixel value 0 represents the background.

  • Each segment is labeled with an ID from 1 to 255.

  • If multiple segments cover the same pixel, the ID of the segment written last takes precedence.

  • If there are more than 255 segments, the 255th and all subsequent segments use ID 255.

Use the region map:

Region IDs only distinguish different segments within the same image. They do not represent object classes. For example, ID 1 does not stand for "person" or any other fixed category.

You can use the region map to compute the foreground ratio, extract or mask specific segments, or map different IDs to colors for visualization. The following example computes the pixel ratio of all segments in the original image:

Existing image operators do not interpret these region IDs automatically. You typically need a custom DataFrame UDF to read the pixel values from the PNG. If you only need to remove the image background, use image_remove_background directly. Example:

from io import BytesIO

import numpy as np
from PIL import Image

from pyflink.dataframe import DataType, col, udf
from pyflink.multimodal.operators import image_segment

result = df.with_column(
    "region_map_png",
    image_segment(
        col("image"),
        confidence=0.1
    )
)

@udf(return_dtype=DataType.float64())
def foreground_ratio(region_map_png):
    if region_map_png is None:
        return None
    with Image.open(BytesIO(region_map_png)) as region_map:
        labels = np.asarray(region_map, dtype=np.uint8)
    return float((labels != 0).mean())

result = result.with_column(
    "foreground_ratio",
    foreground_ratio(col("region_map_png"))
)

image_ocr

Dependency: pip install easyocr

Extract text from images using EasyOCR.

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

Signature:

image_ocr(
    *columns,
    lang=None,
    model_sharing=None,
    concurrency=None,
    batch_size=None,
    num_gpus=None,
    gpu_type=None
)

Parameter

Type

Default

Description

lang

Optional[Union[List[str], Tuple[str, ...]]]

None

A non-empty list or tuple of EasyOCR language codes, such as ["en"] or ("en", "ch_sim"). None uses ["en"].

Note: Only the English OCR model is currently built in. AI functions are recommended for OCR recognition.

Return type:

DataType.list(
    DataType.struct({
        "text": DataType.string(),
        "confidence": DataType.float64(),
        "bbox": DataType.list(
            DataType.list(DataType.float64())
        )
    })
)

bbox keeps the four-point polygon returned by EasyOCR, which represents a text region.

from pyflink.multimodal.operators import image_ocr

result = df.with_column(
    "ocr_results",
    image_ocr(
        col("image"),
        lang=["en", "ch_sim"],
    )
)

image_detect_subplot

Dependency: pip install opencv-python

Determine whether an image is a collage, grid, or subplot based on image edge and grid features, and return the estimated number of sub-images.

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

Signature:

image_detect_subplot(
    *columns,
    threshold=0.5,
    concurrency=None
)

Parameter

Type

Default

Description

threshold

float

0.5

Detection threshold, range [0, 1]. Higher values require more pronounced edges.

Note: Images whose width or height is smaller than 20 pixels always return is_subplot=False and count=1.

Return type:

DataType.struct({
    "is_subplot": DataType.boolean(),
    "count": DataType.int32()
})
from pyflink.multimodal.operators import image_detect_subplot

result = df.with_column(
    "subplot_info",
    image_detect_subplot(
        col("image"),
        threshold=0.6
    )
)

Face processing

image_face_detect

Dependency: pip install opencv-python

Detect faces and return bounding boxes.

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

Signature:

image_face_detect(
    *columns,
    cv_classifier="haarcascade_frontalface_alt.xml",
    min_neighbors=3,
    scale_factor=1.1,
    min_size=None,
    max_size=None,
    concurrency=None
)

Parameter

Type

Default

Description

cv_classifier

str

"haarcascade_frontalface_alt.xml"

Haar Cascade XML file name. Must not contain path separators.

Note: Only the built-in default file is currently supported.

min_neighbors

int

3

Number of neighboring rectangles required to retain a candidate rectangle.

scale_factor

float

1.1

Image pyramid scale factor for multi-scale detection.

min_size

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

None

Minimum face size (width, height). The list must have length 2.

max_size

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

None

Maximum face size (width, height). The list must have length 2.

Return type:

DataType.list(
    DataType.struct({
        "x": DataType.int32(),
        "y": DataType.int32(),
        "w": DataType.int32(),
        "h": DataType.int32(),
        "confidence": DataType.float64()
    })
)

Note: Haar Cascade does not provide per-box probabilities, so confidence is currently always None.

from pyflink.multimodal.operators import image_face_detect

result = df.with_column(
    "faces",
    image_face_detect(
        col("image"),
        min_neighbors=5,
        min_size=(32, 32)
    )
)

image_face_count

Dependency: pip install opencv-python

Count the number of faces in an image.

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

Signature:

image_face_count(
    *columns,
    cv_classifier="haarcascade_frontalface_alt.xml",
    min_neighbors=3,
    scale_factor=1.1,
    min_size=None,
    max_size=None,
    concurrency=None
)

Parameter

Type

Default

Description

cv_classifier

str

"haarcascade_frontalface_alt.xml"

Haar Cascade XML file name. Must not contain path separators.

Note: Only the built-in default file is currently supported.

min_neighbors

int

3

Number of neighboring rectangles required to retain a candidate rectangle.

scale_factor

float

1.1

Image pyramid scale factor for multi-scale detection.

min_size

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

None

Minimum face size (width, height). The list must have length 2.

max_size

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

None

Maximum face size (width, height). The list must have length 2.

Return type: DataType.int32().

Note: Null input returns None. A valid image with no detected faces returns 0.

from pyflink.multimodal.operators import image_face_count

result = df.with_column(
    "face_count",
    image_face_count(col("image"))
)

image_face_blur

Dependency: pip install opencv-python

Detect faces and blur the face regions.

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

Signature:

image_face_blur(
    *columns,
    cv_classifier="haarcascade_frontalface_alt.xml",
    blur_type="gaussian",
    radius=2,
    min_neighbors=3,
    scale_factor=1.1,
    min_size=None,
    max_size=None,
    concurrency=None
)

Parameter

Type

Default

Description

cv_classifier

str

"haarcascade_frontalface_alt.xml"

Haar Cascade XML file name. Must not contain path separators.

Note: Only the built-in default file is currently supported.

blur_type

str

"gaussian"

Blur algorithm: "gaussian" or "box".

radius

float

2

Blur radius. Must be a finite non-negative number.

min_neighbors

int

3

Number of neighboring rectangles required to retain a candidate rectangle.

scale_factor

float

1.1

Image pyramid scale factor for multi-scale detection.

min_size

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

None

Minimum face size (width, height). The list must have length 2.

max_size

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

None

Maximum face size (width, height). The list must have length 2.

Return type: DataType.image().

from pyflink.multimodal.operators import image_face_blur

result = df.with_column(
    "anonymized",
    image_face_blur(
        col("image"),
        blur_type="gaussian",
        radius=12
    )
)