専門ユニット2/山内研セミナー(2021/11/30)

関連サイトと資料

プログラム

import cv2
from IPython.display import Image, display
  
def imshow(title, img):
    """ndarray 配列をインラインで Notebook 上に表示する。
    """
    ret, encoded = cv2.imencode('.png', img)
    print(title)
    display(Image(encoded))
    

import cv2
  
face_cascade = cv2.CascadeClassifier('./cascades/haarcascade_frontalface_default.xml')
img = cv2.imread('woodcutters.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.08, 5)
  
for (x, y, w, h) in faces:
  img = cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
  
cv2.imwrite('./woodcutters_detected.jpg', img)
imshow('detected faces', img)
    

import cv2
  
face_cascade = cv2.CascadeClassifier('./cascades/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('./cascades/haarcascade_eye.xml')
  
camera = cv2.VideoCapture(0)
while (cv2.waitKey(1) == -1):
  success, frame = camera.read()
  if success:
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5, minSize=(120, 120))
    for (x, y, w, h) in faces:
      cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
      roi_gray = gray[y:y+h, x:x+w]
      eyes = eye_cascade.detectMultiScale(roi_gray, 1.03, 5, minSize=(40, 40))
      for (ex, ey, ew, eh) in eyes:
        cv2.rectangle(frame, (x+ex, y+ey), (x+ex+ew, y+ey+eh), (0, 255, 0), 2)
  
    cv2.imshow('Face Detection', frame)
  
cv2.destroyAllWindows()
camera.release()
    

import cv2
import os
  
listName = ['kato', 'ban', 'kino', 'yago', 'yama']
index = 4 # 自分の名前のインデックスを代入してください
output_folder = f'./face_imgs/{listName[index]}'
if not os.path.exists(output_folder):
  os.makedirs(output_folder)
  
face_cascade = cv2.CascadeClassifier('./cascades/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('./cascades/haarcascade_eye.xml')
  
camera = cv2.VideoCapture(0)
count = 0
while (cv2.waitKey(1) == -1):
  success, frame = camera.read()
  if success:
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5, minSize=(120, 120))
  
    for (x, y, w, h) in faces:
      cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
      face_img = cv2.resize(gray[y:y+h, x:x+w], (200, 200))
      face_filename = os.path.join(output_folder, f'{count+1:04}.png')
      cv2.imwrite(face_filename, face_img)
      count += 1
      print(f'\r{count}', end='')
  
    cv2.imshow('Capturing Faces...', frame)
  
cv2.destroyAllWindows()
camera.release()
    

import numpy as np
import os
import cv2
  
def read_images(path, image_size):
  names = []
  training_images, training_labels = [], []
  label = 0
  
  for dirname, subdirnames, filenames in os.walk(path):
    for subdirname in subdirnames:
      names.append(subdirname)
      subject_path = os.path.join(dirname, subdirname)
  
      for filename in os.listdir(subject_path):
        img = cv2.imread(os.path.join(subject_path, filename), cv2.IMREAD_GRAYSCALE)
  
        if img is None:
          # The file cannot be loaded as an image.
          # Skip it.
          continue
        img = cv2.resize(img, image_size)
        training_images.append(img)
        training_labels.append(label)
  
      label += 1
    
  training_images = np.asarray(training_images, np.uint8)
  training_labels = np.asarray(training_labels, np.int32)
  return names, training_images, training_labels
    

import pickle
  
names_filename = 'names.pickle'
path_to_training_images = './face_imgs'
training_image_size = (200, 200)
names, training_images, training_labels = read_images(path_to_training_images, training_image_size)
  
with open(names_filename, 'wb') as f1:
  pickle.dump(names, f1)
    

import cv2
  
model = cv2.face.EigenFaceRecognizer_create()
model.train(training_images, training_labels)
model.save('EigenFace.yaml')      
    

import cv2
import pickle
  
model = cv2.face.EigenFaceRecognizer_create()
model.read('EigenFace.yaml')
  
names_filename = 'names.pickle'
with open(names_filename, 'rb') as f2:
  names = pickle.load(f2)
  
face_cascade = cv2.CascadeClassifier('./cascades/haarcascade_frontalface_default.xml')
  
camera = cv2.VideoCapture(0)
  
while (cv2.waitKey(1) == -1):
  success, frame = camera.read()
  if success:
    faces = face_cascade.detectMultiScale(frame, 1.3, 5)
  
    for (x, y, w, h) in faces:
      cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
      gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
      roi_gray = gray[x:x+w, y:y+h]
  
      if roi_gray.size == 0:
        # The ROI is empty. Maybe the face is at the image edge.
        # Skip it.
        continue
  
      roi_gray = cv2.resize(roi_gray, training_image_size)
      label, confidence = model.predict(roi_gray)
      text = f'{names[label]}, confidence={confidence:.2}'
      cv2.putText(frame, text, (x, y - 20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
  
    cv2.imshow('Face Recognition', frame)
  
cv2.destroyAllWindows()
camera.release()
    

import cv2
  
model = cv2.face.FisherFaceRecognizer_create()
model.train(training_images, training_labels)
model.save('FisherFace.yaml')      
    

import cv2
import pickle
  
model = cv2.face.FisherFaceRecognizer_create()
model.read('FisherFace.yaml')
  
names_filename = 'names.pickle'
with open(names_filename, 'rb') as f2:
  names = pickle.load(f2)
  
face_cascade = cv2.CascadeClassifier('./cascades/haarcascade_frontalface_default.xml')
  
camera = cv2.VideoCapture(0)
  
while (cv2.waitKey(1) == -1):
  success, frame = camera.read()
  if success:
    faces = face_cascade.detectMultiScale(frame, 1.3, 5)
  
    for (x, y, w, h) in faces:
      cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
      gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
      roi_gray = gray[x:x+w, y:y+h]
  
      if roi_gray.size == 0:
        # The ROI is empty. Maybe the face is at the image edge.
        # Skip it.
        continue
  
      roi_gray = cv2.resize(roi_gray, training_image_size)
      label, confidence = model.predict(roi_gray)
      text = f'{names[label]}, confidence={confidence:.2}'
      cv2.putText(frame, text, (x, y - 20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
  
    cv2.imshow('Face Recognition', frame)
  
cv2.destroyAllWindows()
camera.release()
    

import cv2
  
model = cv2.face.LBPHFaceRecognizer_create()
model.train(training_images, training_labels)
model.save('LBPHFace.yaml')      
    

import cv2
import pickle
  
model = cv2.face.LBPHFaceRecognizer_create()
model.read('LBPHFace.yaml')      
  
names_filename = 'names.pickle'
with open(names_filename, 'rb') as f2:
  names = pickle.load(f2)
  
face_cascade = cv2.CascadeClassifier('./cascades/haarcascade_frontalface_default.xml')
  
camera = cv2.VideoCapture(0)
  
while (cv2.waitKey(1) == -1):
  success, frame = camera.read()
  if success:
    faces = face_cascade.detectMultiScale(frame, 1.3, 5)
  
    for (x, y, w, h) in faces:
      cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
      gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
      roi_gray = gray[x:x+w, y:y+h]
  
      if roi_gray.size == 0:
        # The ROI is empty. Maybe the face is at the image edge.
        # Skip it.
        continue
  
      roi_gray = cv2.resize(roi_gray, training_image_size)
      label, confidence = model.predict(roi_gray)
      text = f'{names[label]}, confidence={confidence:.2}'
      cv2.putText(frame, text, (x, y - 20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
  
    cv2.imshow('Face Recognition', frame)
  
cv2.destroyAllWindows()
camera.release()