I want to cut a polygon from a photo and move it to another place in the photo and I want to plot the final image with ggplot2
.
I use the terra
package (feel free to suggest a better approach/method) to convert the photo into a data.frame
which is necessary for ggplot2
:
# load libraries
library(terra)
library(ggplot2)
# download the cat photo from internet (its an open source photo)
cat_url = "https://images.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg?auto=compress&cs=tinysrgb&w=600"
download.file(url = cat_url, destfile = "cat.jpeg")
# return the full path to the cat photo
cat_path = list.files(pattern = "cat.jpeg", full.names = TRUE)
# load the cat photo as rast from terra
cat_rast = rast(cat_path)
# convert the rast file into a dataframe containing the pixels in red, green and blue channels
cat_df = as.data.frame(cat_rast, xy = TRUE) # xy = TRUE returns x and y coordinates as 1st and 2nd columns
I can now plot the red channel of the image using ggplot2
:
# plot red channel with ggplot2
ggplot(data = cat_df, aes(x, y, fill = cat_1)) + # cat_1 corresponds to the 1st channel in the image, which is red
geom_raster() +
coord_fixed(xlim = c(0, 1.5), ylim = c(0, 1.5))
which produces:
What I want to do at this point is to cut a polygon from the left side of the image and move all the pixels contained in the polygon to the right side of the image. I also want to cut a polygon from the bottom and move it up.
Using photoshop:
Here, the drawn "polygon" on the left should then be moved to the right side of the image and the drawn "polygon" on the bottom should be moved to the upper side of the image.
2
Answers
You can draw polygons like this
predefined polygon
Crop/mask the image with the polygon and shift it to the right or top
Remove the area from the original and merge
Set RGB channels again and plot (here using base-plot)
If you want to do this all within ggplot, perhaps it is just as easy to select which pixels you want to move and move them. For the curves you have drawn, the pixels are bounded by simple quadratic curves, so you could do: