0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Microsoft Azure Cognitive Services Faceを動作させてみる その3

Last updated at Posted at 2020-03-05

その2からの続きです。

付録

##以下のSnippetをJupyter-notebookのセルに順番に張り付けてKEY、ENDPOINTを設定すると動作するはずです。PERSON_GROUP_IDの値は任意です。

FaceQuickstartのsnippet_imports部分.py
# <snippet_imports>
import asyncio
import io
import glob
import os
import sys
import time
import uuid
import requests
from urllib.parse import urlparse
from io import BytesIO
from PIL import Image, ImageDraw
from azure.cognitiveservices.vision.face import FaceClient
from msrest.authentication import CognitiveServicesCredentials
from azure.cognitiveservices.vision.face.models import TrainingStatusType, Person, SnapshotObjectType, OperationStatusType
# </snippet_imports>
FaceQuickstartのsnippet_subvars部分.py
# <snippet_subvars>
# Set the FACE_SUBSCRIPTION_KEY environment variable with your key as the value.
# This key will serve all examples in this document.
# KEY = os.environ['FACE_SUBSCRIPTION_KEY']
KEY = "12345678901234567890123456789012"

# Set the FACE_ENDPOINT environment variable with the endpoint from your Face service in Azure.
# This endpoint will be used in all examples in this quickstart.
# ENDPOINT = os.environ['FACE_ENDPOINT']
ENDPOINT = "https://1234567890.cognitiveservices.azure.com/"

# <snippet_persongroupvars>
# Used in the Person Group Operations,  Snapshot Operations, and Delete Person Group examples.
# You can call list_person_groups to print a list of preexisting PersonGroups.
# SOURCE_PERSON_GROUP_ID should be all lowercase and alphanumeric. For example, 'mygroupname' (dashes are OK).
PERSON_GROUP_ID = 'my-unique-person-group'

# </snippet_subvars>
FaceQuickstartのsnippet_auth部分.py
# <snippet_auth>
# Create an authenticated FaceClient.
face_client = FaceClient(ENDPOINT, CognitiveServicesCredentials(KEY))
# </snippet_auth>
FaceQuickstartのsnippet_persongroup_create部分.py
# <snippet_persongroup_create>
# Create empty Person Group. Person Group ID must be lower case, alphanumeric, and/or with '-', '_'.
print('Create Person group:', PERSON_GROUP_ID)
face_client.person_group.create(person_group_id=PERSON_GROUP_ID, name=PERSON_GROUP_ID)

# Define woman friend
woman = face_client.person_group_person.create(PERSON_GROUP_ID, "Woman")
# Define man friend
man = face_client.person_group_person.create(PERSON_GROUP_ID, "Man")
# Define child friend
child = face_client.person_group_person.create(PERSON_GROUP_ID, "Child")
# </snippet_persongroup_create>
FaceQuickstartのsnippet_persongroup_assign部分.py
# <snippet_persongroup_assign>
# Find all jpeg images of friends in working directory
woman_images = [file for file in glob.glob('*.jpg') if file.startswith("woman")]
man_images = [file for file in glob.glob('*.jpg') if file.startswith("man")]
child_images = [file for file in glob.glob('*.jpg') if file.startswith("child")]

from IPython.display import Image, display_jpeg

print('test-image-person-group.jpg')
display_jpeg(Image('test-image-person-group.jpg')) 

# Add to a woman person
for image in woman_images:
    w = open(image, 'r+b')
    face_client.person_group_person.add_face_from_stream(PERSON_GROUP_ID, woman.person_id, w)
    # png_file: str
    print(str(image))
    display_jpeg(Image(image)) 

# Add to a man person
for image in man_images:
    m = open(image, 'r+b')
    face_client.person_group_person.add_face_from_stream(PERSON_GROUP_ID, man.person_id, m)
    # png_file: str
    print(str(image))
    display_jpeg(Image(image)) 

# Add to a child person
for image in child_images:
    ch = open(image, 'r+b')
    face_client.person_group_person.add_face_from_stream(PERSON_GROUP_ID, child.person_id, ch)
    # png_file: str
    print(str(image))
    display_jpeg(Image(image)) 

from PIL import Image, ImageDraw
# </snippet_persongroup_assign>
FaceQuickstartのsnippet_persongroup_train部分.py
# <snippet_persongroup_train>
print()
print('Training the person group...')
# Train the person group
face_client.person_group.train(PERSON_GROUP_ID)

while (True):
    training_status = face_client.person_group.get_training_status(PERSON_GROUP_ID)
    print("Training status: {}.".format(training_status.status))
    print()
    if (training_status.status is TrainingStatusType.succeeded):
        break
    elif (training_status.status is TrainingStatusType.failed):
        sys.exit('Training the person group has failed.')
    time.sleep(5)
# </snippet_persongroup_train>
FaceQuickstartのsnippet_identify_testimage部分.py
# <snippet_identify_testimage>
# Group image for testing against
group_photo = 'test-image-person-group.jpg'
IMAGES_FOLDER = os.path.join(os.path.dirname(os.path.realpath("__file__")))
# Get test image
test_image_array = glob.glob(os.path.join(IMAGES_FOLDER, group_photo))
image = open(test_image_array[0], 'r+b')

# Detect faces
face_ids = []
faces = face_client.face.detect_with_stream(image)
print('test-image-person-group.jpgに含まれるface_id: ')
for face in faces:
    face_ids.append(face.face_id)
    print(face.face_id)
# </snippet_identify_testimage>
FaceQuickstartのsnippet_identify部分.py
# <snippet_identify>
print('each person_id')
print('woman face_id: ' + woman.person_id)
print('man face_id: ' + man.person_id)
print('child face_id: ' + child.person_id)

# Identify faces
results = face_client.face.identify(face_ids, PERSON_GROUP_ID)
print('Identifying faces in {}'.format(os.path.basename(image.name)))
if not results:
    print('No person identified in the person group for faces from {}.'.format(os.path.basename(image.name)))
for person in results:
    print('Person for face ID {} is identified in {} with a confidence of {}.'.format(person.face_id, os.path.basename(image.name), person.candidates[0].confidence)) 
    print(str(person.candidates[0].person_id))
    
# </snippet_identify>
FaceQuickstartで単純にPersonGroupを削除する.py
print('delete person_group_id')
face_client.person_group.delete(person_group_id=PERSON_GROUP_ID)

PersonGroupからPersonを削除するサンプルソース

PersonGroupからPersonを削除する.py
# delete person_id from PERSON_GROUP
# PersonGroupに含まれるpersonのリストを作成
dictlist = face_client.person_group_person.list(PERSON_GROUP_ID, start=None, top=None, custom_headers=None, raw=False)

# personのリストからnameとidを取り出して、XXXと合致するnameの場合のidをdeleteメソッドに渡して該当するpersonを削除する
for delete_person in dictlist:
    candidate_name = delete_person.name
    candidate_person_id = delete_person.person_id
    print('candidate_name:' + str(candidate_name))
    print('candidate_person_id:' + str(candidate_person_id))
    if candidate_name == 'XXX':
        face_client.person_group_person.delete(PERSON_GROUP_ID, candidate_person_id, custom_headers=None, raw=False)
        print('deleted name:' + candidate_name)

# その後、PersonGroupをトレーニングしてpersonの削除を反映させる
print('Training the person group...')
# Train the person group
face_client.person_group.train(PERSON_GROUP_ID)

while (True):
    training_status = face_client.person_group.get_training_status(PERSON_GROUP_ID)
    print("Training status: {}.".format(training_status.status))
    print()
    if (training_status.status is TrainingStatusType.succeeded):
        break
    elif (training_status.status is TrainingStatusType.failed):
        sys.exit('Training the person group has failed.')
    time.sleep(5)

以上です。ご覧いただき、ありがとうございました!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?