rimage-processingmagick

R magick: Square crop and circular mask


The aim is to

  1. convert any input image to square aspect ratio and
  2. add a circular mask and fill the outside with white or transparency.

I have got 1 to work, but not sure it's the best way to do it. Here is a working example.

library(magick)
path <- "https://cdn.pixabay.com/photo/2016/08/17/21/12/people-1601516_960_720.jpg"
img <- magick::image_read(path)
img

Original image

enter image description here

ii <- magick::image_info(img)
ii_min <- min(ii$width,ii$height)
img1 <- magick::image_crop(img, geometry=paste0(ii_min,"x",ii_min,"+0+0"),repage=TRUE)
img1

Cropped Square Aspect Ratio

enter image description here

I am not sure how to get the last part (2) to work in R. Although I have sort of managed to get it to work using image-magick in unix.

convert -size 500x500 xc:white -fill cropped.jpeg -draw "circle 250,250 250,1" circ.jpg

Circular Frame

enter image description here

I am looking for a solution to 2 in R.


Solution

  • library(magick)
    path <- "https://cdn.pixabay.com/photo/2016/08/17/21/12/people-1601516_960_720.jpg"
    im <- magick::image_read(path)
    
    # get height, width and crop longer side to match shorter side
    ii <- magick::image_info(im)
    ii_min <- min(ii$width, ii$height)
    im1 <- magick::image_crop(im, geometry=paste0(ii_min, "x", ii_min, "+0+0"), repage=TRUE)
    
    # create a new image with white background and black circle
    fig <- magick::image_draw(image_blank(ii_min, ii_min))
    symbols(ii_min/2, ii_min/2, circles=(ii_min/2)-3, bg='black', inches=FALSE, add=TRUE)
    dev.off()
    
    # create an image composite using both images
    im2 <- magick::image_composite(im1, fig, operator='copyopacity')
    
    # set background as white
    magick::image_background(im2, 'white')
    

    enter image description here

    R version 4.0.0
    magick_2.5.2