item_transform_crop: Crop a dataset item

View source: R/item-transforms-geometry.R

item_transform_cropR Documentation

Crop a dataset item

Description

Crops the image inside a dataset item at the specified location and output size. For detection items, bounding box coordinates are adjusted to remain correct after cropping. For segmentation items, both the image and the masks are cropped. For rotated-box items, box coordinates are adjusted and the rotation angle is preserved. If the crop area extends beyond the image boundaries, boxes that fall completely outside the crop are removed, and boxes that intersect the crop boundary are clipped to the cropped region.

Usage

item_transform_crop(x, top, left, height, width)

Arguments

x

A dataset item, typically an image_with_bounding_box or image_with_segmentation_mask object containing an image tensor and associated target data.

top

integer: Vertical component of the top left corner of the crop box.

left

integer: Horizontal component of the top left corner of the crop box.

height

integer: Height of the crop box.

width

integer: Width of the crop box.

Value

A dataset item of the same class with the cropped image and adjusted target.

See Also

Other item_unitary_transforms: item_transform_affine(), item_transform_center_crop(), item_transform_hflip(), item_transform_pad(), item_transform_perspective(), item_transform_resize(), item_transform_rotate(), item_transform_vflip()

Examples

## Not run: 
url <- "https://upload.wikimedia.org/wikipedia/commons/b/b6/Felis_catus-cat_on_snow.jpg"
img <- base_loader(url) |> transform_to_tensor()

boxes <- torch_tensor(matrix(c(600, 200, 2880, 1860), ncol = 4), dtype = torch_float32())

before <- list(x = img, y = list(boxes = boxes, labels = "cat"))
class(before) <- c("image_with_bounding_box", "list")

after <- item_transform_crop(before, top = 100, left = 200, height = 500, width = 800)

before_plot <- before %>%
  draw_bounding_boxes(colors = "blue", width = 10) %>%
  transform_resize(c(2000, 3000))
after_plot <- after %>%
  draw_bounding_boxes(colors = "red", width = 10) %>%
  transform_resize(c(2000, 3000))

tensor_image_browse(vision_make_grid(before_plot, after_plot, scale = TRUE))

## End(Not run)


torchvision documentation built on Oct. 14, 2026, 1:09 a.m.