From c7a575d38a7ac3259c677bfa7e79727e63ffc97a Mon Sep 17 00:00:00 2001 From: jkessler93 Date: Thu, 2 Mar 2023 16:37:08 -0800 Subject: [PATCH] Adds new functions to plotBoxes.R that crop images and save them to an output file --- R/plotBoxes.R | 64 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/R/plotBoxes.R b/R/plotBoxes.R index d299231..dbfc9a7 100644 --- a/R/plotBoxes.R +++ b/R/plotBoxes.R @@ -58,3 +58,67 @@ plotBoxes <- function(image, label = FALSE, minconf = 0) { } } } + +library(magick) +#' Crops a jpg image using a precalculated bounding box +#' +#' @param imagePath The path for the image +#' @param bbox1 bounding box coordinate corresponding to the left edge of the box +#' @param bbox2 bounding box coordinate corresponding to the bottom edge of the box +#' @param bbox3 bounding box coordinate corresponding to the right edge of the box +#' @param bbox4 bounding box coordinate corresponding to the top edge of the box +#' +#' @return no return value, outputs the cropped image +#' @export +#' +#' @examples +#' \dontrun{ +#' cropJpg("/image/path/image.jpg", "/output/path/", 0.1, 0.2, 0.6, 0.8) +#' } +cropJpg <- function(imagePath, outputPath, bbox1, bbox2, bbox3, bbox4) { + image <- image_read(imagePath) + info <- image_info(image) + width <- info$width + height <- info$height + + xleft <- bbox1 * width + ybottom <- height - bbox2 * height + xright <- (bbox1 + bbox3) * width + ytop <- height - (bbox2 + bbox4) * height + + width <- xright - xleft + height <- ybottom - ytop + + dimensions <- paste(width, height, sep="x") + dimensions <- paste(dimensions, xleft, ytop, sep="+") + cropped <- image_crop(image, dimensions) + + split_image_path_vector <- strsplit(imagePath, "/") + image_name <- split_image_path_vector[[1]][length(split_image_path_vector[[1]])] + output_path <- paste(outputPath, image_name) + image_write(cropped, path = output_path, format = "png") +} + +#' Crops all images from an input file with specific required columns: Frame, +#' bbox1, bbox2, bbox3, and bbox4 +#' +#' @param csvFilePath The path for the input csv file +#' @param outputPath The path where generated cropped images should be uploaded +#' +#' @return no return value, outputs the cropped image +#' @export +#' +#' @examples +#' \dontrun{ +#' cropImagesFromFile("/image/path/file.csv", "/output/path/") +#' } +cropImagesFromFile <- function(csvFilePath, outputPath) { + uncropped_data <- read.csv(csvFilePath) + df = data.frame(uncropped_data) + df <- as.data.frame(sapply(df, function(x) gsub("\"", "", x))) # Removes extra quotation marks + + # for-loop over rows + for(i in 1:nrow(df)) { + cropJpg(df[i,]$Frame,outputPath,as.numeric(df[i,]$bbox1),as.numeric(df[i,]$bbox2),as.numeric(df[i,]$bbox3),as.numeric(df[i,]$bbox4)) + } +}