xwMOOC 딥러닝
정보과학교육연합회-R을 이용한 인공지능 튜토리얼
학습 목표
- 본인 나이, 사진속 얼굴 나이, 기계가 판단하는 나이를 비교한다.
- 인공지능 API 서비스의 다양한 면을 살펴본다.
- 인공지능 API 코딩 실습을 통해 코딩교육의 방향을 (나름) 설정한다.
1. R을 이용한 인공지능 튜토리얼
2. 나이측정 인공지능 서비스 1
2.1. 나이측정 앱서비스
2.2. 나이측정 API 둘러보기
2.3. 나이측정 API 개발 사용자 인터페이스
- 사전 준비물
- 구독 열쇠(subscription keys) : https://www.microsoft.com/cognitive-services/en-us/apis
- 사진 url: https://raw.githubusercontent.com/statkclee/2016-11-06-sogang/gh-pages/figure/angry-face.jpg
- 매개변수: returnFaceAttributes : Age,Gender,Smile,FacialHair,HeadPose,Glasses
- 마이크로소프트 Cognitive Services
- Face API → API reference → Open API Testing Console : 실습 웹콘솔
3. 코딩
이미지를 컴퓨터에 넣어 이미지에 들어있는 사람얼굴을 인식하고 사람얼굴을 숫자로 뽑아내는 실습을 진행한다.
3.1. Lena 이미지 불러오기
가장 먼저 R로 이미지를 불러온다. 메모리에 적재되어 중앙처리장치를 통해 R로 만든 명령어를 수행하기 위한 선행작업이다.
library(dplyr)
library(ggplot2)
# install.packages("png")
# install.packages("grid")
library(png)
library(grid)
par(mar=c(0,0,0,0))
plot.new()
readPNG("02_data/lena.png")
lena <-rasterImage(lena,0,0,1,1)
3.2. Lena 이미지 얼굴 위치 파악
## 1. Lena 이미지
library(httr)
Warning: package 'httr' was built under R version 4.0.2
par(mar=c(0,0,0,0))
plot.new()
readPNG("02_data/lena.png")
lena <-rasterImage(lena,0,0,1,1, interpolate = TRUE)
## 2. 얼굴 위치 파악
httr::upload_file("02_data/lena.png")
img <-
"https://api.projectoxford.ai/face/v1.0/detect?returnFaceLandmarks=true&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses"
face_api_url =
# faceKEY <- '53xxxxxxxxxxxxxxxxxxxxxxxxxx'
source("03_code/private-keys.R")
Warning in file(filename, "r", encoding = encoding): cannot open file '03_code/
private-keys.R': No such file or directory
Error in file(filename, "r", encoding = encoding): cannot open the connection
POST(url = face_api_url,
result <-body = img,
add_headers(.headers = c('Content-Type' = 'application/octet-stream',
'Ocp-Apim-Subscription-Key' = faceKEY))
)
Error in request(headers = c(..., .headers)): object 'faceKEY' not found
as.data.frame(content(result)) face_df <-
Error in is.response(x): object 'result' not found
## 3. 얼굴 위치 사각형 표시
data.frame(x1 = face_df$faceRectangle.left,
rect <-x2 = face_df$faceRectangle.left + face_df$faceRectangle.width,
y1 = dim(lena)[1] - face_df$faceRectangle.top,
y2 = dim(lena)[1] - face_df$faceRectangle.top - face_df$faceRectangle.height)
Error in data.frame(x1 = face_df$faceRectangle.left, x2 = face_df$faceRectangle.left + : object 'face_df' not found
data.frame(0:dim(lena)[2], 0:dim(lena)[1])
df <-
rasterGrob(lena, interpolate=TRUE)
g <-
ggplot(df) +
scale_x_continuous(limits = c(0, 512)) +
scale_y_continuous(limits = c(0, 512)) +
annotation_custom(g, xmin=0, xmax=dim(lena)[2], ymin=0, ymax=dim(lena)[1]) +
geom_rect(data=rect, mapping=aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2), color="blue", alpha=0.0) +
coord_fixed()
Error in f(...): 'list' object cannot be coerced to type 'double'
3.3. 수지 감정
## 00. 환경설정 ==========================================================================================
library("httr")
library("XML")
library("ggplot2")
## 01. 마이크로소프트 API 설정 ==========================================================================================
# 적용할 마이크로소프트 API 지정
'https://api.projectoxford.ai/emotion/v1.0/recognize'
URL.emoface <-
# 접속 인증키 설정
# emotionKEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
source("03_code/private-keys.R")
Warning in file(filename, "r", encoding = encoding): cannot open file '03_code/
private-keys.R': No such file or directory
Error in file(filename, "r", encoding = encoding): cannot open the connection
## 02. 감정분석할 이미지 지정 및 호출 ==========================================================================================
httr::upload_file("02_data/suji.jpg")
img <- "https://api.projectoxford.ai/emotion/v1.0/recognize"
emotion_api_url =
POST(url = emotion_api_url,
suji_face <-body = img,
add_headers(.headers = c('Content-Type' = 'application/octet-stream',
'Ocp-Apim-Subscription-Key' = emotionKEY))
)
Error in request(headers = c(..., .headers)): object 'emotionKEY' not found
## 03. 감정분석결과 추가분석 (Suji Face) ==========================================================================================
# 얼굴 분석결과
httr::content(suji_face)[[1]] suji_face_lst <-
Error in is.response(x): object 'suji_face' not found
as.data.frame(suji_face_lst[2]) %>% t %>% as.data.frame suji_face_df <-
Error in as.data.frame(suji_face_lst[2]): object 'suji_face_lst' not found
$V1 <- lapply(strsplit(as.character(suji_face_df$V1), "e"), "[", 1) suji_face_df
Error in strsplit(as.character(suji_face_df$V1), "e"): object 'suji_face_df' not found
$V1 <- as.numeric(suji_face_df$V1) suji_face_df
Error in eval(expr, envir, enclos): object 'suji_face_df' not found
colnames(suji_face_df)[1] <- "Level"
Error in colnames(suji_face_df)[1] <- "Level": object 'suji_face_df' not found
$Emotion <- sub("scores.", "", rownames(suji_face_df)) suji_face_df
Error in rownames(suji_face_df): object 'suji_face_df' not found
# 시각화
ggplot(suji_face_df, aes(x=Emotion, y=Level)) +
geom_bar(stat="identity")
Error in ggplot(suji_face_df, aes(x = Emotion, y = Level)): object 'suji_face_df' not found
suji_face_df
Error in eval(expr, envir, enclos): object 'suji_face_df' not found
3.4. 사진속 나이
# 0. 환경설정--------------------------------------------------
library(httr)
library(XML)
library(ggplot2)
library(png)
library(grid)
library(jsonlite)
Warning: package 'jsonlite' was built under R version 4.0.3
library(dplyr)
# 1. 데이터 불러오기 ----------------------------------------------
list.files("02_data/")
img_list <-
# 2. 얼굴인식 API 호출 ------------------------------------------------
"https://api.projectoxford.ai/face/v1.0/detect?returnFaceAttributes=age,gender"
face_api_url <-
# faceKEY <- '53xxxxxxxxxxxxxxxxxx'
source("03_code/private-keys.R")
Warning in file(filename, "r", encoding = encoding): cannot open file '03_code/
private-keys.R': No such file or directory
Error in file(filename, "r", encoding = encoding): cannot open the connection
list()
img_bucket <-
for(lst in seq_along(img_list)){
paste0("02_data/", img_list[lst])
img_name <- httr::upload_file(img_name)
img <-
POST(url = face_api_url,
result <-body = img,
add_headers(.headers = c('Content-Type' = 'application/octet-stream',
'Ocp-Apim-Subscription-Key' = faceKEY))
)
as.data.frame(content(result))[,c("faceAttributes.gender", "faceAttributes.age")]
img_bucket[[lst]] <- }
Error in request(headers = c(..., .headers)): object 'faceKEY' not found
# 3. 데이터 정리-------------------------------------
do.call(rbind, img_bucket)
img_buckets <-
data.frame(idate=img_list, img_buckets) img_buckets <-
Error in data.frame(idate = img_list, img_buckets): arguments imply differing number of rows: 5, 0
img_buckets %>%
img_buckets <- rename(gender = faceAttributes.gender, age=faceAttributes.age)
Warning: `rename_()` is deprecated as of dplyr 0.7.0.
Please use `rename()` instead.
This warning is displayed once every 8 hours.
Call `lifecycle::last_warnings()` to see where this warning was generated.
Error in UseMethod("rename_"): no applicable method for 'rename_' applied to an object of class "NULL"
img_buckets
NULL