Last active
February 17, 2019 23:03
-
-
Save shaun-jacks/004a822a48b947df76ac8c502a43f5ce to your computer and use it in GitHub Desktop.
Code to render facial image using R graphics device and magick library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# We first create an image pointer with image_read(/path/to/image) | |
photo = magick::image_read(values$file_path) | |
# obtain photo dimensions | |
photo_info = magick::image_info(photo) | |
height = photo_info$height | |
max_height <- 400 # this variable is used for height parameter within renderImage() | |
rescale_lwd <- 2/max_height * height # rescale our line widths when drawing | |
# draw original image without analysis features | |
magick::image_draw(photo) | |
######################## | |
#### FACE DETECTION #### | |
######################## | |
facial_features_found <- !is.null(values$img_res$fdBoundingPoly$vertices) | |
if (facial_features_found) { | |
# loop through each face found with mapply | |
mapply(bboxes = values$img_res$fdBoundingPoly$vertices, # bounding boxes | |
lbl_id = c(1:length(values$img_res$fdBoundingPoly$vertices)), # label by number | |
facial_pts = values$img_res$landmarks, # landmark points | |
function(bboxes, lbl_id, facial_pts) { | |
# Draw bounding box polygons for each face found | |
polygon(x = bboxes[[1]], y = bboxes[[2]], border = 'red', | |
lwd = rescale_lwd) # rescaled line width | |
# Draw label id's on top of each bounding box | |
text(x = bboxes[[1]][[3]], y = bboxes[[2]][[3]], | |
labels = as.character(lbl_id), # label each image with an id | |
offset = 1, | |
cex = 3, # text magnified by this factor relative to default | |
col = "white") | |
# Draw facial landmark points | |
points(x = facial_pts$position$x, # plot the x coordinates of facial landmarks | |
y = facial_pts$position$y, # plot the y coordinates of facial landmarks | |
col = "green", | |
lwd = rescale_lwd, | |
pch = 3) | |
}) | |
} else { # else, no features were detected | |
text(x = width/2, y = height/2, labels = "No features detected", col = "red", | |
offset = 1, cex = 5) | |
} | |
# save image with graphics output drawings to image pointer | |
photo = magick::image_capture() | |
dev.off() | |
# store it into a temporary file for imageOutput UI | |
tmpFile <- image_write(photo, tempfile(fileext='jpg'), format = 'jpg') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment