Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions R/plotBoxes.R
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
}