Skip to main content

Function Signature

Description

Calculates optimal image dimensions that satisfy multiple constraints simultaneously:
  1. Both dimensions are divisible by factor
  2. Total pixels are within [min_pixels, max_pixels] range
  3. Aspect ratio is maintained as closely as possible
This function is used internally by fetch_image and fetch_video to ensure images are properly sized for vision-language models.

Parameters

int
required
Original image height in pixels.
int
required
Original image width in pixels.
int
required
Both output dimensions must be divisible by this factor.Typically calculated as: image_patch_size * SPATIAL_MERGE_SIZE
  • For patch size 14: factor = 28
  • For patch size 16: factor = 32
Optional[int]
default:"IMAGE_MIN_TOKEN_NUM * factor²"
Minimum total pixels allowed in the resized image.Default: 4 * factor² (IMAGE_MIN_TOKEN_NUM = 4)
Optional[int]
default:"IMAGE_MAX_TOKEN_NUM * factor²"
Maximum total pixels allowed in the resized image.Default: 16384 * factor² (IMAGE_MAX_TOKEN_NUM = 16384)

Returns

int
New height divisible by factor, maintaining aspect ratio within pixel constraints.
int
New width divisible by factor, maintaining aspect ratio within pixel constraints.

Algorithm

The function follows this logic:
  1. Round to factor: Round both dimensions to nearest multiple of factor
  2. Check max constraint: If height * width > max_pixels:
    • Calculate scaling factor: β = sqrt((height * width) / max_pixels)
    • Scale down: new_height = floor(height / β / factor) * factor
  3. Check min constraint: If height * width < min_pixels:
    • Calculate scaling factor: β = sqrt(min_pixels / (height * width))
    • Scale up: new_height = ceil(height * β / factor) * factor

Usage Examples

Basic Usage

With Pixel Constraints

Image Tokens for Vision Models

Aspect Ratio Preservation

Error Handling

Aspect Ratio Too Extreme

The function enforces a maximum aspect ratio of 200:1 to prevent extreme image shapes.

Invalid Pixel Range

Constants

Real-World Examples

Common Image Sizes

Different Patch Sizes

Integration with Other Functions

Used in fetch_image

Used in fetch_video

See Also