I made a Dir en gray face classifier using TensorFlow --⑩ Face classification test

Introduction

――It's finally time to enjoy yourself.

program

eval.py


#!/usr/local/bin/python
#! -*- coding: utf-8 -*-

import sys
import numpy as np
import cv2
import tensorflow as tf
import os
import random
import main

#OpenCV default face classifier path
cascade_path = '/usr/local/Cellar/opencv3/3.2.0/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml'
faceCascade = cv2.CascadeClassifier(cascade_path)

#Identification label and the name corresponding to each label number
HUMAN_NAMES = {
  0: u"Kyo",
  1: u"Kaoru",
  2: u"Shinya"
}

#Specified image(img_path)Learning results(ckpt_path)Judgment using
def evaluation(img_path, ckpt_path):
  #Graph Reset(Apparently, I'm not sure what I'm doing ...)
  tf.reset_default_graph()

  #Open file
  f = open(img_path, 'r')
  img = cv2.imread(img_path, cv2.IMREAD_COLOR)

  #Convert to monochrome image
  gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  face = faceCascade.detectMultiScale(gray, 1.1, 3)

  if len(face) > 0:
    for rect in face:
      #I wanted to give an appropriate name to the processed image because it doesn't matter. Maybe the date and the number of seconds
      random_str = str(random.random())

      #Let's write the face part with a red line
      cv2.rectangle(img, tuple(rect[0:2]), tuple(rect[0:2]+rect[2:4]), (0, 0, 255), thickness=2)

      #Where to save the image with the face surrounded by a red line
      face_detect_img_path = '{Directory path}' + random_str + '.jpg'

      #Saving the image with the face surrounded by a red line
      cv2.imwrite(face_detect_img_path, img)
      x = rect[0]
      y = rect[1]
      w = rect[2]
      h = rect[3]

      #Save the image of the detected face cut out
      cv2.imwrite('{Directory path}' + random_str + '.jpg', img[y:y+h, x:x+w])

      #Cut out face image to pass to TensorFlow
      target_image_path = '{Directory path}' + random_str + '.jpg'
  else:
    #If no face is found, the process ends
    print 'image:No Face'
    return
  f.close()
  f = open(target_image_path, 'r')

  #Array to put data
  image = []
  img = cv2.imread(target_image_path)
  img = cv2.resize(img, (28, 28))

  #After arranging the image information in a row, 0-Set to a float value of 1
  image.append(img.flatten().astype(np.float32)/255.0)
  #Convert to numpy format so that it can be processed by TensorFlow
  image = np.asarray(image)

  #Outputs and returns the probability of each label for the input image(main.Call from py)
  logits = main.inference(image, 1.0)

  # We can just use 'c.eval()' without passing 'sess'
  sess = tf.InteractiveSession()

  # restore(Parameter reading)Preparation of
  saver = tf.train.Saver()

  #Variable initialization
  sess.run(tf.global_variables_initializer())

  if ckpt_path:
    #Reading parameters after learning
    saver.restore(sess, ckpt_path)

  # sess.run(logits)Same as
  softmax = logits.eval()

  #judgment result
  result = softmax[0]

  #Judgment result%And round off
  rates = [round(n * 100.0, 1) for n in result]
  humans = []

  #Create a hash of label numbers, names and percentages
  for index, rate in enumerate(rates):
    name = HUMAN_NAMES[index]
    humans.append({
      'label': index,
      'name': name,
      'rate': rate
    })

  #Sort in descending order of percentage
  rank = sorted(humans, key=lambda x: x['rate'], reverse=True)
  
  #Output results to console
  print rank

  #Returns the judgment result and the path of the processed image
  return [rank, os.path.basename(img_path), random_str + '.jpg']

#For testing from the command line
if __name__ == '__main__':
  evaluation('{Directory path}/test.jpg', '{Directory path}/model2.ckpt')

Run

python eval.py

Supplements and excuses

--Since there is no file such as model2.ckpt, the directory path seems to point to the location where model2.ckpt.index was generated. ――It is successful if you can get the result of how and with what probability the test image resembles who after execution.

All page links

-I made a Dir en gray face classifier using TensorFlow --(1) Introduction -I made a face classifier for Dir en gray using TensorFlow-② Environment construction -I made a face classifier for Dir en gray using TensorFlow-③ Image collection -I made a face classifier for Dir en gray using TensorFlow-④ Face extraction -I made a face classifier for Dir en gray using TensorFlow-⑤ Learning data preparation -I made a Dir en gray face classifier using TensorFlow-⑥ Learning program -I made a face classifier for Dir en gray using TensorFlow-⑦ Learning model -I made a face classifier for Dir en gray using TensorFlow-⑧ Learning execution -I made a Dir en gray face classifier using TensorFlow --⑨ Data visualization -I made a Dir en gray face classifier using TensorFlow --⑩ Face classification test -I made a Dir en gray face classifier using TensorFlow-⑪ Web release preparation -I made a Dir en gray face classifier using TensorFlow --⑫ Web release -I tried to make a Dir en gray face classifier using TensorFlow --⑬ Playing (final)

Recommended Posts

I made a Dir en gray face classifier using TensorFlow --⑩ Face classification test
I made a Dir en gray face classifier using TensorFlow --(1) Introduction
I made a Dir en gray face classifier using TensorFlow-④ Face extraction
I made a Dir en gray face classifier using TensorFlow --⑥ Learning program
I made a Dir en gray face classifier using TensorFlow --⑬ Playing (final)
I made a Dir en gray face classifier using TensorFlow --- ⑧ Learning execution
I made a Dir en gray face classifier using TensorFlow --⑫ Web release
I made a Dir en gray face classifier using TensorFlow --- ⑦ Learning model
I made a Dir en gray face classifier using TensorFlow --② Environment construction
I made a Dir en gray face classifier using TensorFlow --⑪ Web release preparation
I made a VGG16 model using TensorFlow (on the way)
Make a face recognizer using TensorFlow
Face detection using a cascade classifier
I tried playing a ○ ✕ game using TensorFlow
Beginner: I made a launcher using dictionary
I tried to make a ○ ✕ game using TensorFlow
I made a login / logout process using Python Bottle.
[Python] I made a classifier for irises [Machine learning]
I made a school festival introduction game using Ren’py
〇✕ I made a game
I made a quick feed reader using feedparser in Python
I tried hosting a TensorFlow deep learning model using TensorFlow Serving
I made a face diagnosis AI for a female professional golfer ③
I made a muscle training estimation app using Qore SDK
I made a Chatbot using LINE Messaging API and Python
I tried face recognition using Face ++
I made a python text
I tried using magenta / TensorFlow
I made a discord bot
I made a game called Battle Ship using pygame and tkinter
Python> I made a test code for my own external file
I tried scoring a transvestite contest using Face ++'s Detect API
I made a poker game server chat-holdem using websocket with python
I made a Chatbot using LINE Messaging API and Python (2) ~ Server ~
[Kaggle] I made a collection of questions using the Titanic tutorial