Microsoft Azure Cognitive Face API를 이용하여 Instagram 이미지 분석하기

Microsoft Azure Cognitive Face API를 이용하여 Instagram의 이미지를 분석하는 작은 프로젝트를 해봤습니다. 언어는 Python을 사용합니다.

목차

  1. Instagram 사진 다운받기
  2. Face API 등록
  3. 코드 작성

1. Instagram 사진 다운받기

먼저 Instagram의 이미지를 다운받기 위해 Instagram Scraper를 다운받아야합니다.

  • github 링크 : https://github.com/rarcega/instagram-scraper
    • 설치 방법

      $ pip install instagram-scraper

    • 피드명을 @feed, 인스타그램 id를 @id, password를 @pw라고 했을 때 다음 명령어를 입력하면 사진을 다운로드 받을 수 있습니다.

      $ instagram-scraper @feed -u @id -p @pw

2. Face API 등록

Face key를 받기 위해 Face API에 들어가서 계정을 등록합니다. 기간 한정 무료로 이용할 수 있습니다.

계정 등록을 하면 Face Key를 얻어올 수 있습니다.

3. 코드 작성

  • 아래 코드들은 @feed 부분과 path 부분을 각자 상황에 맞게 수정해야 돌아간다.
  • 필요한 모듈과 Face key, face url 지정
import requests, os, json, time
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import pprint
from PIL import Image
face_key = # '2번에서 얻어온 Face Key'
face_url = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect'
headers    = {
    'Ocp-Apim-Subscription-Key': face_key,
    'Content-Type': 'application/octet-stream'
}

params = {
    'returnFaceId': 'true',
    'returnFaceLandmarks': 'true',
    'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,' +
    'emotion,hair,makeup,occlusion,accessories,blur,exposure,noise',
    'recognitionModel': 'recognition_02',
    'returnRecognitionModel': 'true'
}

def face_api(filename):
    with open(filename, "rb") as f:
        body = f.read()
    try:
        response = requests.post(face_url, headers=headers, params=params, data=body)
        results = response.json()
    except Exception as e:
        print(e)
        results = None
    return results

image_list = os.listdir(#'@feed')
save_path = './save/'
# 숨김파일 제거
image_list = [photo_name for photo_name in apple_image_list if not photo_name.startswith('.')]

with open(save_path + "result.jsonl", 'a') as f:
    for image in image_list:
        if image.endswith('jpg'):
            photo = #'./@feed/' + image
            results = face_api(photo)
            photo_dict = {}
            photo_dict[image] = results
            f.write(json.dumps(photo_dict) + '\n')
            time.sleep(3) # 무료로 이용할 땐 3초에 1번씩 요청할 수 있기 때문에 sleep이 필요하다.
  • 이제 작성된 jsonl 파일을 가지고 평균 얼굴의 갯수와 감정의 갯수를 구하는 예제를 풀 수 있다.
face_results = []
with open(save_path + "result.jsonl", 'r') as f:
    for line in f:
        face_results.append(json.loads(line))

face_count = []
for result in face_results:
    face_count.append(len(list(result.values())[0]))

anger, contempt, disgust, fear, happiness, neutral, sadness, surprise = [], [], [], [], [], [], [], []
for result in face_results:
    faces = list(result.values())[0]
    if len(faces) != 0:
        for face in faces:
            anger.append(face['faceAttributes']['emotion']['anger'])
            contempt.append(face['faceAttributes']['emotion']['contempt'])
            disgust.append(face['faceAttributes']['emotion']['disgust'])
            fear.append(face['faceAttributes']['emotion']['fear'])
            happiness.append(face['faceAttributes']['emotion']['happiness'])
            neutral.append(face['faceAttributes']['emotion']['neutral'])
            sadness.append(face['faceAttributes']['emotion']['sadness'])
            surprise.append(face['faceAttributes']['emotion']['surprise'])

print("평균 얼굴 개수 : " + str(np.mean(face_count)))
print("anger : " + str(np.mean(anger)))
print("contempt : " + str(np.mean(contempt)))
print("disgust : " + str(np.mean(disgust)))
print("fear : " + str(np.mean(fear)))
print("happiness : " + str(np.mean(happiness)))
print("neutral : " + str(np.mean(neutral)))
print("sadness : " + str(np.mean(sadness)))
print("surprise : " + str(np.mean(surprise)))
  • plt를 이용하여 pie 그래프로 나타낼 수도 있다.
emotion = ['anger', 'contempt', 'disgust', 'fear', 'hapiness', 'neutral', 'sadness', 'surprise']
popuratity = [np.mean(anger), np.mean(contempt), np.mean(disgust), np.mean(fear), np.mean(happiness), np.mean(neutral),
             np.mean(sadness), np.mean(surprise)]
colors = ['blue', 'orange', 'green', 'red', 'violet', 'brown', 'gold', 'yellowgreen'] 
explode = (0, 0, 0, 0, 0, 0, 0, 0)  

plt.figure(figsize=(12, 12))
plt.pie(popuratity, explode=explode, labels=emotion, textprops={'fontsize': 15}, colors=colors, autopct='%1.1f%%', shadow=True)
print("@Apple emotion")
plt.show()
  • 위 코드의 결과

Image

+ Recent posts