Search code examples
rmagick

Crop out circle from image and lay over second image


I have two images where I'd like to cut out a circle and lay that image atop another one. However, I struggle to achieve that. Here, the two input images and the desired output:

Input image 1: Input image 1 Input image 2: Input image 2 Desired output: output image

Here is my attempt:

library(magick)
library(dplyr)

p1 <- image_read("https://i.sstatic.net/uLypl.jpg") 
p2 <- image_read("https://i.sstatic.net/bkd1M.jpg") 

# Inspect
# p1 |> image_scale("20%")
# p2 |> image_scale("20%")

ii <- magick::image_info(p1)
factx <- 5.48
facty <- 3.95

im1 <- image_crop(p2, geometry=paste0(ii$width/factx, "x", ii$height/facty, "+0+0"), 
                      gravity="center")

# Inspect
# im1 |> image_scale("20%")

fig <- image_draw(image_blank(ii$width/factx, ii$width/factx))
symbols(ii$width/factx/2, ii$width/factx/2, circles=(ii$width/factx/2), bg='black', inches=FALSE, add=TRUE)
dev.off()

im2 <- image_composite(im1, fig, operator='minus')#
# image_background(im2, 'white') |> image_scale("20%")

im3 <- image_background(im2, 'white')

# Inspect
image_composite(p1, im3, gravity="center")|> image_scale("20%")

However, this results in sth not desired. The point is not blue but black and there seems to be a square around the circle: the not desired output

Thanks for any help!


Solution

  • Below R code will produce what you expect with much less operation.

    library(magick)
    library(dplyr)
    
    p1 <- image_read("https://i.sstatic.net/uLypl.jpg") 
    p2 <- image_read("https://i.sstatic.net/bkd1M.jpg")  
    
    ii <- magick::image_info(p1)
    factx <- 5.48
    facty <- 3.95
    
    fig <- image_draw(image_blank(ii$width/factx, ii$width/factx, color = "none"))    
    symbols(ii$width/factx/2, ii$width/factx/2, circles=(ii$width/factx/2), bg='blue', inches=FALSE, add=TRUE)
    dev.off()
    
    image_composite(p1, fig, gravity="center")|> image_scale("20%")
    

    Notify that in image_blank() method color = "none" should be set. In symbols() the argument bg should be set to: bg='blue'.

    Then you can directly composite P1 and fig. The result in my Rstudio is in below image:

    enter image description here