Hey everyone,
I have been given an image (PNG file) and a data frame of a bunch of coordinates, in the units of pixels relative to the image, and asked to draw polygons on top of the image using the coordinates. I have made some progress on getting this to work, but can’t get the pixel coordinates to line up with the ggplot coordinates. I have provided a MWE using the R logo below. My questions are:
1) is the general approach I took make sense? I have not worked with images like this before, and found this method by searching the web
2) if this is the right approach, how do I correctly plot the polygon?
###
library(png)
library(grid)
img <- readPNG("~/Desktop/Rlogo.png")
g <- rasterGrob(img)
xy <- data.frame(x = c(80, 80, 116, 116, 80), y = c(42, 155, 155, 42, 42))
# The original coordinates are standard computer graphics, where positive y goes down, so I need to transform them to cartesian
xy_transform <- xy
xy_transform$y <- nrow(g$raster) - xy$y
library(ggplot2)
ggplot(xy_transform) +
annotation_custom(g, -Inf, Inf, -Inf, Inf) +
geom_polygon(aes(x = x, y = y), color = "red", fill = "red", alpha = 0.5) +
xlim(c(0, ncol(g$raster))) + ylim(c(0, nrow(g$raster)))
ggsave("~/Desktop/Rlogo-R.pdf”)
###
I have attached the output from ggplot as well as what the actual pixels look like when I draw the same rectangle using GIMP.
Thanks!
Doug