オリジナルは http://blog.hoxo-m.com/2017/04/10/imager/

library("imager")
u <- "https://raw.githubusercontent.com/dichika/ojisan/master/takayanagi_dj.jpg" #DJタカヤナギ
dj <- load.image(u)
print(dj)
## Image. Width: 960 pix Height: 720 pix Depth: 1 Colour channels: 3
plot(dj, axes = FALSE)

ojisan <- load.image("https://raw.githubusercontent.com/dichika/ojisan/master/sakura4.jpg") # 別のおじさん
plot(ojisan, axes = FALSE)

ojisan_mod <- ojisan %>% resize(size_x = 500, size_y = 500)
MS_FACE_KEY="ほげほげ"
tmp <- tempfile(fileext = ".png")
ojisan_mod %>% save.image(tmp)

library("httr")
url_base <- "https://westus.api.cognitive.microsoft.com/face/v1.0/detect"
result <- POST(url_base, 
               body = upload_file(tmp), 
               query = list(returnFaceAttributes="age,gender,headPose,smile,facialHair,glasses,emotion", 
                            language="en"), 
               add_headers(.headers = c(`Content-Type`="application/octet-stream", 
                                        `Ocp-Apim-Subscription-Key`=MS_FACE_KEY
               )
               )
) %>% content()
bbox <- result[[1]]$faceRectangle
ojisan_sub <- ojisan_mod %>% imsub(x %inr% c(bbox$left, bbox$left + bbox$width),
                                   y %inr% c(bbox$top, bbox$top + bbox$height))
plot(ojisan_sub, axes = FALSE)

これってもしかして

tmp2 <- tempfile(fileext = ".png")
dj %>% save.image(tmp2)

library("httr")
url_base <- "https://westus.api.cognitive.microsoft.com/face/v1.0/detect"
result2 <- POST(url_base, 
               body = upload_file(tmp2), 
               query = list(returnFaceAttributes="age,gender,headPose,smile,facialHair,glasses,emotion", 
                            language="en"), 
               add_headers(.headers = c(`Content-Type`="application/octet-stream", 
                                        `Ocp-Apim-Subscription-Key`=MS_FACE_KEY
               )
               )
) %>% content()
bbox2 <- result2[[1]]$faceRectangle
dj_sub <- dj %>% imsub(x %inr% c(bbox2$left, bbox2$left + bbox2$width),
                                   y %inr% c(bbox2$top, bbox2$top + bbox2$height))
plot(dj_sub, axes = FALSE)

おじさんたち

ojisan_on_takayanagisan = ojisan_sub %>% resize(size_x = bbox2$width, size_y = bbox2$height)
dj_ojisan <- dj %>% imdraw(ojisan_on_takayanagisan, x = bbox2$left, y = bbox2$top, opacity = 0.9)
plot(dj_ojisan, axes = FALSE)

入れ替わってる〜〜!?

ぜんぜんぜんぜー♫