Implementation:Tensorflow Tfjs CenterCrop Layer
Appearance
| 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.cropAndResizewith normalized box coordinates computed from the center offset buffers. Handles rank-3 inputs by temporarily stacking to rank-4. - upsize: Falls back to
image.resizeBilinearwhen 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
- Tensorflow_Tfjs_Resizing_Layer - Image resizing preprocessing layer
- Tensorflow_Tfjs_Rescaling_Layer - Pixel value rescaling layer
- Tensorflow_Tfjs_RandomHeight_Layer - Random height augmentation layer
- Tensorflow_Tfjs_RandomWidth_Layer - Random width augmentation layer
Page Connections
Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment