图像检测与人脸处理

更新时间:
复制 MD 格式

本文介绍 Python DataFrame API 中的目标检测、图像分割、文字识别、子图检测和人脸处理算子。

使用前须知

  • 仅实时计算引擎 VVR 11.8 及以上版本支持。

  • 模型相关算子支持跑在 CPU 或 GPU 之上,根据是否配置了 GPU 资源自动选择 device。

算子清单

分类

算子

说明

检测与识别

image_detect_objects

使用 YOLO 检测目标物体。

image_segment

使用 FastSAM 生成图像分割掩码。

image_ocr

使用 EasyOCR 从图像中提取文字。

image_detect_subplot

判断图像是否为拼接图并返回子图数量。

人脸处理

image_face_detect

检测人脸并返回边界框。

image_face_count

统计图像中的人脸数量。

image_face_blur

对人脸区域进行模糊处理。

通用 Runtime 参数

函数签名保留各算子实际支持的 Runtime 参数。为避免重复,算子参数表只说明业务参数,Runtime 参数统一说明如下。本页模型类算子包括 image_detect_objectsimage_segmentimage_ocr

参数

类型

默认值

说明

concurrency

Optional[int]

None

UDF 并发度。None 表示使用框架默认值。

model_sharing

Optional[str]

None

模型共享方式。None 表示使用框架默认值。

batch_size

Optional[int]

None

Batch UDF 批大小。None 表示使用框架默认值。

num_gpus

Optional[float]

None

每个模型实例申请的 GPU 数量或份额,例如 0.5

gpu_type

Optional[str]

None

GPU 类型,与 num_gpus 配套设置。

检测与识别

image_detect_objects

使用 YOLO 检测目标物体。

输入类型: DataType.image(),解码后的图像列。

依赖: pip install ultralytics

函数签名:

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
)

参数

类型

默认值

说明

model

str

"yolov8n"

YOLO 模型名称或路径。目前仅内置支持 yolov8n 模型。

confidence

float

0.05

最小检测置信度,取值范围为 [0, 1]

imgsz

int

640

推理分辨率,必须为正整数。

iou

float

0.5

NMS 的 IoU 阈值,取值范围为 [0, 1]

返回类型:

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

xy 是边界框左上角坐标,wh 是边界框宽度和高度。

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

使用 FastSAM 生成图像分割掩码图。

输入类型: DataType.image(),解码后的图像列。

依赖: pip install ultralytics

函数签名:

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
)

参数

类型

默认值

说明

model

str

"FastSAM-x.pt"

FastSAM 模型名称或路径。目前仅内置支持 FastSAM-x.pt 模型。

confidence

float

0.05

最小置信度,取值范围为 [0, 1]

imgsz

int

1024

推理分辨率,必须为正整数。

iou

float

0.5

NMS 的 IoU 阈值,取值范围为 [0, 1]

返回类型: DataType.binary(),内容为 PNG 格式的区域编号图。

区域编号图中:

  • 像素值 0 表示背景。

  • 每个分割区域使用 1255 的数字编号表示。

  • 同一像素被多个区域覆盖时,以最后写入分割图的区域编号为准。

  • 分割区域超过 255 个时,第 255 个及之后的区域都使用编号 255

使用区域编号图:

区域编号只用于区分同一张图像中的不同区域,不表示物体类别。例如,编号 1 不能代表“人”或其他固定类别。

可以通过区域编号图统计前景占比、提取或遮挡指定区域,也可以将不同编号映射为颜色后生成可视化结果。以下示例计算所有分割区域在原图中的像素占比:

现有图像算子不会自动解释这些区域编号,通常需要使用自定义 DataFrame UDF 读取 PNG 中的像素值。如果只需要移除图像背景,可直接使用 image_remove_background。使用示例如下:

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

使用 EasyOCR 从图像中提取文字。

输入类型: DataType.image(),解码后的图像列。

依赖: pip install easyocr

函数签名:

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

参数

类型

默认值

说明

lang

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

None

非空的 EasyOCR 语言代码列表或元组,例如 ["en"]("en", "ch_sim")None 使用 ["en"]

注意,当前仅内置了英文 OCR 模型,推荐使用 AI function 进行 OCR 识别。

返回类型:

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

bbox 保留 EasyOCR 返回的四点多边形,可以表示文字区域。

from pyflink.multimodal.operators import image_ocr

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

image_detect_subplot

使用图像边缘和网格特征判断图像是否为拼接图、宫格图或子图,并返回估计的子图数量。

输入类型: DataType.image(),解码后的图像列。

依赖: pip install opencv-python

函数签名:

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

参数

类型

默认值

说明

threshold

float

0.5

检测阈值,取值范围为 [0, 1]。值越大,要求边缘越明显。

注意:宽度或高度小于 20 像素时固定返回 is_subplot=Falsecount=1

返回类型:

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
    )
)

人脸处理

image_face_detect

检测人脸并返回边界框。

输入类型: DataType.image(),解码后的图像列。

依赖: pip install opencv-python

函数签名:

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
)

参数

类型

默认值

说明

cv_classifier

str

"haarcascade_frontalface_alt.xml"

Haar Cascade XML 文件名,不能包含路径分隔符。

注意:当前仅支持内置默认值文件

min_neighbors

int

3

每个候选矩形需要保留的相邻矩形数量。

scale_factor

float

1.1

多尺度检测的图像金字塔缩放比例。

min_size

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

None

最小人脸尺寸 (width, height),列表长度必须为 2。

max_size

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

None

最大人脸尺寸 (width, height),列表长度必须为 2。

返回类型:

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

注意:Haar Cascade 不提供逐框概率,因此 confidence 当前始终为 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

统计图像中的人脸数量。

输入类型: DataType.image(),解码后的图像列。

依赖: pip install opencv-python

函数签名:

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
)

参数

类型

默认值

说明

cv_classifier

str

"haarcascade_frontalface_alt.xml"

Haar Cascade XML 文件名,不能包含路径分隔符。

注意:当前仅支持内置默认值文件

min_neighbors

int

3

每个候选矩形需要保留的相邻矩形数量。

scale_factor

float

1.1

多尺度检测的图像金字塔缩放比例。

min_size

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

None

最小人脸尺寸 (width, height),列表长度必须为 2。

max_size

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

None

最大人脸尺寸 (width, height),列表长度必须为 2。

返回类型: DataType.int32()

备注:空值输入返回 None;有效图片中未检测到人脸时返回 0

from pyflink.multimodal.operators import image_face_count

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

image_face_blur

检测人脸并对人脸区域进行模糊处理。

输入类型: DataType.image(),解码后的图像列。

依赖: pip install opencv-python

函数签名:

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
)

参数

类型

默认值

说明

cv_classifier

str

"haarcascade_frontalface_alt.xml"

Haar Cascade XML 文件名,不能包含路径分隔符。

注意:当前仅支持内置默认值文件

blur_type

str

"gaussian"

模糊方式。支持 "gaussian""box"

radius

float

2

模糊半径,必须为有限的非负数。

min_neighbors

int

3

每个候选矩形需要保留的相邻矩形数量。

scale_factor

float

1.1

多尺度检测的图像金字塔缩放比例。

min_size

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

None

最小人脸尺寸 (width, height),列表长度必须为 2。

max_size

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

None

最大人脸尺寸 (width, height),列表长度必须为 2。

返回类型: 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
    )
)