xwMOOC 딥러닝

정보과학교육연합회-R을 이용한 인공지능 튜토리얼

학습 목표

  • 본인 나이, 사진속 얼굴 나이, 기계가 판단하는 나이를 비교한다.
  • 인공지능 API 서비스의 다양한 면을 살펴본다.
  • 인공지능 API 코딩 실습을 통해 코딩교육의 방향을 (나름) 설정한다.

1. R을 이용한 인공지능 튜토리얼

R 인공지능 튜토리얼 일정

2. 나이측정 인공지능 서비스 1

인공지능 서비스

2.1. 나이측정 앱서비스

2.2. 나이측정 API 둘러보기

2.3. 나이측정 API 개발 사용자 인터페이스

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()

lena <- readPNG("02_data/lena.png")
rasterImage(lena,0,0,1,1)

plot of chunk dl-read-raw-image

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()

lena <- readPNG("02_data/lena.png")
rasterImage(lena,0,0,1,1, interpolate = TRUE)

plot of chunk dl-image-location

## 2. 얼굴 위치 파악
img <- httr::upload_file("02_data/lena.png")

face_api_url = "https://api.projectoxford.ai/face/v1.0/detect?returnFaceLandmarks=true&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses"

# 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
result <- POST(url = face_api_url,
               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
face_df <- as.data.frame(content(result))
Error in is.response(x): object 'result' not found
## 3. 얼굴 위치 사각형 표시

rect <- data.frame(x1 = face_df$faceRectangle.left,
                   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
df <- data.frame(0:dim(lena)[2], 0:dim(lena)[1])


g <- rasterGrob(lena, interpolate=TRUE)

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'

plot of chunk dl-image-location

3.3. 수지 감정

## 00. 환경설정  ========================================================================================== 
library("httr")
library("XML")
library("ggplot2")

## 01. 마이크로소프트 API 설정 ==========================================================================================

# 적용할 마이크로소프트 API 지정
URL.emoface <- 'https://api.projectoxford.ai/emotion/v1.0/recognize'

# 접속 인증키 설정
# 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. 감정분석할 이미지 지정 및 호출 ==========================================================================================

img <- httr::upload_file("02_data/suji.jpg")
emotion_api_url = "https://api.projectoxford.ai/emotion/v1.0/recognize"

suji_face <- POST(url = emotion_api_url,
            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) ==========================================================================================
# 얼굴 분석결과
suji_face_lst <- httr::content(suji_face)[[1]]
Error in is.response(x): object 'suji_face' not found
suji_face_df <- as.data.frame(suji_face_lst[2]) %>% t %>% as.data.frame
Error in as.data.frame(suji_face_lst[2]): object 'suji_face_lst' not found
suji_face_df$V1 <- lapply(strsplit(as.character(suji_face_df$V1), "e"), "[", 1)
Error in strsplit(as.character(suji_face_df$V1), "e"): object 'suji_face_df' not found
suji_face_df$V1 <- as.numeric(suji_face_df$V1)
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
suji_face_df$Emotion <- sub("scores.", "", rownames(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. 데이터 불러오기 ----------------------------------------------

img_list <- list.files("02_data/")

# 2. 얼굴인식 API 호출 ------------------------------------------------

face_api_url <- "https://api.projectoxford.ai/face/v1.0/detect?returnFaceAttributes=age,gender"

# 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
img_bucket <- list()

for(lst in seq_along(img_list)){
  img_name <- paste0("02_data/", img_list[lst])
  img <- httr::upload_file(img_name)
  
  result <- POST(url = face_api_url,
                 body = img,
                 add_headers(.headers = c('Content-Type' = 'application/octet-stream',
                                          'Ocp-Apim-Subscription-Key' = faceKEY))
  )
  
  img_bucket[[lst]] <- as.data.frame(content(result))[,c("faceAttributes.gender", "faceAttributes.age")]
}
Error in request(headers = c(..., .headers)): object 'faceKEY' not found
# 3. 데이터 정리-------------------------------------

img_buckets <- do.call(rbind, img_bucket)

img_buckets <- data.frame(idate=img_list, 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

  1. How to Detect Faces in Image↩︎