You need to enable JavaScript to run this app.
Lake AI Service

Lake AI Service

Copy page
Download PDF
Video processing
Video cropping
Copy page
Download PDF
Video cropping

Operator introduction

Description

Video cropping processor that supports multiple cropping modes and parameter configurations.

Key features:

  • Multiple cropping modes:
    • Precise cropping based on bounding box
    • Resolution-based cropping
    • Aspect ratio-based cropping
    • Multiple cropping positions (center, top, bottom, left, right)
  • Encoding mode support:
    • CPU encoding (libx264): quality prioritized
    • GPU encoding (h264_nvenc): speed prioritized
  • Automatic audio stream processing: keeps audio unaffected
  • Multiple input and output methods: supports path input, binary input, and TOS output
  • Fine quality control: adjustable encoding parameters and quality settings

Format support:

  • Input: MP4, AVI, MOV, and other mainstream video formats
  • Output: consistent with input format

Parameter priority:

  • Bounding box (bbox) > target resolution (target_width/target_height) > aspect ratio (aspect_ratio)

Caution and prerequisites

Details

Caution and prerequisites

Costs

Before calling an operator, you need to understand the model invocation costs associated with using the operator. For details, see Large model invocation billing.

Authentication (API Key)

Before calling an operator, you need to generate an API Key for operator invocation. It is recommended to configure the API Key as an environment variable to ensure safer operator calls. For details, see Obtain and configure API Key.

BaseURL

Before calling an operator, you need to determine the BaseURL for operator invocation based on the region where your current LAS service is deployed. This is used to configure the path parameter values for operator calls.
For details, see Obtain the Base URL. The Examples below are for reference only; when making actual calls, replace the path values with those corresponding to your region.

Daft invocation

Operator parameters

Input

Input column names

Note

video_paths

Video file path column (local, TOS, HTTP, and so on), choose either video_paths or video_binaries

video_binaries

Video binary data column, choose either video_binaries or video_paths

video_formats

Video format string column, used with video_binaries

output_basenames

Output file base name column (without extension)

Output

An array containing the paths of cropping results. Returns the output path on success, returns an empty string on failure.

Parameters

If a parameter does not have a default value, it is required.

Parameter name

Type

Default value

Description

output_tos_dir

str

Saves the cropped video to this TOS or local directory. If empty, the video is not saved. Format: "tos://bucket/path/", or local directory path.

target_width

int or None

Target video width, used with target_height to specify the exact resolution.
Unit: pixels
Default value: None

target_height

int or None

Target video height, used with target_width to specify the exact resolution.
Unit: pixels
Default value: None

aspect_ratio

float or None

Target aspect ratio, format: width/height (for example, 16/9=1.7778).
Default value: None

bbox

tuple[int, int, int, int] or None

Bounding box parameter, format is (x, y, width, height).
x, y: coordinates of the top-left corner of the cropping area
width, height: width and height of the cropping area
Priority is higher than target_width/target_height and aspect_ratio
Default value: None

crop_mode

str

"center"

Cropping mode.
center: center cropping
top: Crop from top
bottom: Crop from bottom
left: Crop from left
right: Crop from right
Optional values: ["center", "top", "bottom", "left", "right"]
Default value: "center"

force_divisible_by

int

2

Pixel alignment step, ensures width and height are divisible by this value.
Default value: 2

crf

float

23.0

Constant quality factor for the libx264 encoder.
Applicable: Used only for CPU encoding (libx264)
Range: 0.0–51.0. The lower the value, the higher the quality and the larger the file size.
Recommended: 18 (high quality), 23 (balanced), 28 (compression prioritized)
Default value: 23.0

preset

str

"medium"

Encoding speed preset for the libx264 encoder.
Applicable: Used only for CPU encoding (libx264)
Trade-off: Speed ↔ Compression efficiency
Optional values: ["ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow"]
Recommended: "medium" (balanced), "fast" (speed prioritized), "slow" (quality prioritized)
Default value: "medium"

cq

float

0

Quality control parameter for the NVENC encoder.
Applicable: Used only for GPU encoding (h264_nvenc)
Range: 0–51. 0 indicates automatic quality control.
Recommended: 0 (automatic) or 18–28 (manual control)
Default value: 0

rc

str

"vbr"

Bitrate control mode for the NVENC encoder.
Applicable: Used only for GPU encoding (h264_nvenc)
constqp: Constant quantization parameter, stable quality
vbr: Variable bitrate, balances quality and file size
cbr: Constant bitrate, suitable for streaming
Recommended: "vbr" (general), "cbr" (live streaming)
Default value: "vbr"

rank

int or None

Specifies the GPU device number to use (effective in multi-GPU environments).
Note: 0 indicates the first GPU, 1 indicates the second GPU, None indicates automatic selection
Applicable: Effective only for GPU encoding
Default value: None

Examples

The following code demonstrates how to use Daft (for distributed scenarios) to run the operator for video cropping.

from __future__ import annotations

import os

import daft
from daft import col
from daft.las.functions.udf import las_udf
from daft.las.functions.video.video_crop import VideoCrop

if __name__ == "__main__":
    # The cropped video will be saved to the specified TOS path. Therefore, you need to set environment variables to ensure you have write permissions for TOS, including: ACCESS_KEY, SECRET_KEY, TOS_ENDPOINT, TOS_REGION, TOS_TEST_DIR
    TOS_TEST_DIR = os.getenv("TOS_TEST_DIR", "your-bucket")
    output_tos_dir = f"tos://{TOS_TEST_DIR}/video_crop"
    
    if os.getenv("DAFT_RUNNER", "native") == "ray":
        import logging

        import ray

        def configure_logging():
            logging.basicConfig(
                level=logging.INFO,
                format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
                datefmt="%Y-%m-%d %H:%M:%S",
            )
            logging.getLogger("tracing.span").setLevel(logging.WARNING)
            logging.getLogger("daft_io.stats").setLevel(logging.WARNING)
            logging.getLogger("DaftStatisticsManager").setLevel(logging.WARNING)
            logging.getLogger("DaftFlotillaScheduler").setLevel(logging.WARNING)
            logging.getLogger("DaftFlotillaDispatcher").setLevel(logging.WARNING)

        ray.init(dashboard_host="0.0.0.0", runtime_env={"worker_process_setup_hook": configure_logging})
        daft.set_runner_ray()
    daft.set_execution_config(actor_udf_ready_timeout=600)
    daft.set_execution_config(min_cpu_per_task=0)

    # Construct the URL using environment variables
    tos_dir_url = os.getenv("TOS_DIR_URL", "las-cn-beijing-public-online.tos-cn-beijing.volces.com")
    samples = {
        "video_path": [
            f"https://{tos_dir_url}/public/shared_video_dataset/sample.mp4"
        ]
    }

    ds = daft.from_pydict(samples)

    cropper = las_udf(
        VideoCrop,
        construct_args={
            "output_tos_dir": output_tos_dir,
            "target_width": 1280,
            "target_height": 720,
            "crop_mode": "center",
        },
        num_cpus=1,
        concurrency=1,
        batch_size=1,
    )

    # Use Daft for distributed processing
    ds = ds.with_column("crop_result", cropper(col("video_path")))

    ds.show()
    # ╭────────────────────────────────┬────────────────────────────────╮
    # │ video_path                     ┆ crop_result                    │
    # │ ---                            ┆ ---                            │
    # │ Utf8                           ┆ Utf8                           │
    # ╞════════════════════════════════╪════════════════════════════════╡
    # │ https://las-cn-beijing-publi-… ┆ tos://your-bucket/video_crop/… │
    # ╰────────────────────────────────┴────────────────────────────────╯
Last updated: 2026.05.22 11:14:25