item_transform_perspective: Apply a perspective transform to a dataset item

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

item_transform_perspectiveR Documentation

Apply a perspective transform to a dataset item

Description

Applies a perspective transform to the image inside a dataset item, as defined by transform_perspective. For detection items, bounding box coordinates are transformed accordingly and clamped to the image canvas, boxes that end up completely outside the image are removed. For segmentation items, both the image and the masks are transformed, using nearest neighbour interpolation for the masks.

Usage

item_transform_perspective(
  x,
  startpoints,
  endpoints,
  interpolation = 2,
  fill = NULL
)

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.

startpoints

(list of integer vectors of length 2): List containing four integer vectors of length 2 corresponding to four corners ⁠[top-left, top-right, bottom-right, bottom-left]⁠ of the original image.

endpoints

(list of integer vectors of length 2): List containing four integer vectors of length 2 corresponding to four corners ⁠[top-left, top-right, bottom-right, bottom-left]⁠ of the transformed image.

interpolation

(integer, optional): Desired interpolation. An integer 0 = nearest, 2 = bilinear, and 3 = bicubic or a name from magick::filter_types().

fill

(numeric vector or numeric): Pixel fill value for constant fill. Default is 0. If a numeric vector of length 3, it is used to fill R, G, B channels respectively. This value is only used when the padding_mode is constant. Only integer values are supported for Tensors.

Value

A dataset item of the same class with the image and target perspective transformed.

See Also

Other item_unitary_transforms: item_transform_affine(), item_transform_center_crop(), item_transform_crop(), item_transform_hflip(), item_transform_pad(), 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")

startpoints <- list(c(0, 0), c(2880, 0), c(2880, 1860), c(0, 1860))
endpoints <- list(c(100, 50), c(2700, 0), c(2800, 1800), c(80, 1900))

after <- item_transform_perspective(before, startpoints, endpoints)

before_plot <- draw_bounding_boxes(before, colors = "blue", width = 10)
after_plot <- draw_bounding_boxes(after, colors = "red", width = 10)

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.