本文系转载,原博客:http://blog.csdn.net/wzgl__wh/article/details/52904069
使用微软(https://www.microsoft.com/cognitive-services/en-US/subscriptions)的Emotion 来理解一张图片的人物表情,下面直接上代码:
> library("httr")#链接API
> library("XML")#爬取网页数据
> library("stringr")#字符串处理
> library("ggplot2")#绘图使用
> img.url = 'https://www.whitehouse.gov/sites/whitehouse.gov/files/images/first-family/44_barack_obama[1].jpg'
> URL.emoface = 'https://api.projectoxford.ai/emotion/v1.0/recognize'
> emotionKEY = 'b72720c5c1ed4b40a25d00e3db325c32' # 在此处输入你获取的key
> mybody = list(url = img.url)
> faceEMO = POST(
+ url = URL.emoface,
+ content_type('application/json'), add_headers(.headers = c('Ocp-Apim-Subscription-Key' = emotionKEY)),
+ body = mybody,
+ encode = 'json'
+ )
> faceEMO
Response [https://api.projectoxford.ai/emotion/v1.0/recognize]
Date: 2017-01-03 04:23
Status: 200
Content-Type: application/json; charset=utf-8
Size: 259 B
> obama = httr::content(faceEMO)[[1]]
> obama
$faceRectangle
$faceRectangle$height
[1] 269
$faceRectangle$left
[1] 399
$faceRectangle$top
[1] 80
$faceRectangle$width
[1] 269
$scores
$scores$anger
[1] 9.530491e-10
$scores$contempt
[1] 7.204279e-13
$scores$disgust
[1] 2.932419e-09
$scores$fear
[1] 1.770692e-13
$scores$happiness
[1] 1
$scores$neutral
[1] 1.277603e-11
$scores$sadness
[1] 1.228429e-12
$scores$surprise
[1] 1.559173e-10
> o<-as.data.frame(as.matrix(obama$scores))
> o$V1 <- lapply(strsplit(as.character(o$V1 ), "e"), "[", 1)
> o$V1<-as.numeric(o$V1)
> colnames(o)[1] <- "Level"
> o$Emotion<- rownames(o)
> ggplot(data=o, aes(x=Emotion, y=Level)) +
+ geom_bar(stat="identity")
欧巴马的图:
这张图显示他在微笑,但是我们的结果是生气的,看来深度学习还是有改进的空间的。