Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Tensorflow Tfjs CenterCrop Layer

From Leeroopedia


Knowledge Sources
Domains Deep_Learning, Layers_API, Preprocessing
Last Updated 2026-02-10 06:00 GMT

Overview

The CenterCrop layer is an image preprocessing layer that crops images to a target height and width from the center. If the input image is smaller than the target size in either dimension, the layer upsizes the image using bilinear interpolation instead of cropping. The layer supports both 3D (single image) and 4D (batch) tensor inputs and preserves the input dtype.

Code Reference

Source Location

tfjs-layers/src/layers/preprocessing/center_crop.ts (GitHub)

Key Imports

import {serialization, DataType, unstack, stack, tensor, Tensor, Tensor1D, Tensor2D,
        Tensor3D, Tensor4D, tidy, range, image} from '@tensorflow/tfjs-core';
import {LayerArgs, Layer} from '../../engine/topology';
const {resizeBilinear, cropAndResize} = image;

Layer Class

export class CenterCrop extends Layer {
  static className = 'CenterCrop';
  constructor(args: CenterCropArgs);
  centerCrop(inputs, hBuffer, wBuffer, height, width,
             inputHeight, inputWidth, dtype): Tensor | Tensor[];
  upsize(inputs, height, width, dtype): Tensor | Tensor[];
  override call(inputs: Tensor3D | Tensor4D, kwargs: Kwargs): Tensor[] | Tensor;
  override getConfig(): serialization.ConfigDict;
  override computeOutputShape(inputShape: Shape | Shape[]): Shape | Shape[];
}

CenterCropArgs

export interface CenterCropArgs extends LayerArgs {
  height: number;   // target crop height
  width: number;    // target crop width
}

Key Implementation Details

  • centerCrop: Uses image.cropAndResize with normalized box coordinates computed from the center offset buffers. Handles rank-3 inputs by temporarily stacking to rank-4.
  • upsize: Falls back to image.resizeBilinear when the input is smaller than the target dimensions.
  • call: Computes center offsets, chooses between cropping and upsizing based on buffer values, and preserves the original dtype.

I/O Contract

Method Input Output
call 3D or 4D image tensor Tensor cropped/resized to [height, width] spatial dims
computeOutputShape Input shape Shape with height/width set to target values

Usage Example

import * as tf from '@tensorflow/tfjs';

const cropper = tf.layers.centerCrop({height: 224, width: 224});

// Single image
const img = tf.randomNormal([256, 256, 3]);
const cropped = cropper.apply(img);  // shape: [224, 224, 3]

// Batched images
const batch = tf.randomNormal([8, 300, 300, 3]);
const croppedBatch = cropper.apply(batch);  // shape: [8, 224, 224, 3]

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment