Azure AI 102 - Ngày 3

Table of contents

  • Ngày 3:

    • Sáng: Tìm hiểu sâu hơn về Computer Vision: Các khái niệm (Object Detection, Image Classification), Azure AI Vision.

    • Chiều: Thực hành với Azure AI Vision: Phân tích hình ảnh, trích xuất văn bản, phát hiện vật thể.

    • Tối: Ôn tập và làm bài tập:

      • Xây dựng một ứng dụng phát hiện vật thể trong hình ảnh bằng Azure AI Vision.

      • So sánh Image Classification và Object Detection, cho ví dụ ứng dụng.

    • Lưu ý rằng: Bài thi AI - 102, có kiểm tra code, do đó bạn cần đọc hiểu thật kỹ những ví dụ code.

Tìm hiểu sâu hơn về Computer Vision: Các khái niệm (Object Detection, Image Classification), Azure AI Vision.

Computer Vision (Thị giác máy tính) là một lĩnh vực trong trí tuệ nhân tạo (AI) cho phép máy tính và hệ thống hiểu và trích xuất thông tin từ hình ảnh và video. Nó có nhiều ứng dụng trong các lĩnh vực như y tế, tự động hóa, an ninh, và nhiều ngành công nghiệp khác. Ví dụ, các bệnh viện đang sử dụng Computer Vision để phát hiện bệnh từ ảnh chụp y khoa, trong khi các công ty thương mại điện tử sử dụng nó để phân loại sản phẩm.

1. Các khái niệm cơ bản

Image Classification (Phân loại hình ảnh)

Định nghĩa: Image Classification là quá trình gán một nhãn (label) cho toàn bộ hình ảnh dựa trên nội dung của nó. Ví dụ, phân loại một bức ảnh là chó, mèo, hay xe hơi.

Ứng dụng: Phát hiện bệnh từ ảnh chụp y khoa, phân loại sản phẩm trong thương mại điện tử, nhận diện động vật hoang dã từ ảnh camera bẫy.

Object Detection (Phát hiện đối tượng)

Định nghĩa: Object Detection không chỉ phân loại các đối tượng trong hình ảnh mà còn xác định vị trí chính xác của chúng bằng cách vẽ các bounding box xung quanh chúng. Ví dụ, phát hiện và khoanh vùng các xe hơi, người đi bộ trong một bức ảnh chụp đường phố.

Ứng dụng: An ninh giám sát, xe tự lái, quản lý kho hàng, nhận diện khuôn mặt.

2. Các kỹ thuật và mô hình phổ biến trong Computer Vision

Convolutional Neural Networks (CNNs)

Định nghĩa: CNN là loại mạng nơ-ron đặc biệt được thiết kế để xử lý dữ liệu dạng lưới như hình ảnh. CNN sử dụng các lớp convolution để tự động học các đặc điểm của hình ảnh thông qua quá trình huấn luyện.

Ứng dụng: Phân loại hình ảnh, phát hiện đối tượng, phân đoạn hình ảnh.

Region-based Convolutional Neural Networks (R-CNN)

Định nghĩa: R-CNN là một biến thể của CNN, được thiết kế để phát hiện đối tượng. Nó chia hình ảnh thành nhiều vùng và sử dụng CNN để phát hiện đối tượng trong từng vùng.

Các biến thể: Fast R-CNN, Faster R-CNN, và Mask R-CNN.

You Only Look Once (YOLO)

Định nghĩa: YOLO là một phương pháp phát hiện đối tượng theo thời gian thực, giúp mô hình dự đoán cả vị trí và nhãn của đối tượng trong một bước duy nhất.

Ưu điểm: Nhanh và hiệu quả, phù hợp cho các ứng dụng thời gian thực.

Single Shot MultiBox Detector (SSD)

Định nghĩa: SSD là một phương pháp phát hiện đối tượng nhanh và hiệu quả bằng cách sử dụng một mạng nơ-ron duy nhất để dự đoán bounding boxes và nhãn trực tiếp.

Ưu điểm: Cân bằng tốt giữa tốc độ và độ chính xác.

3. Azure AI Vision

Azure AI Vision cung cấp các dịch vụ AI tiên tiến cho Computer Vision, giúp doanh nghiệp tích hợp khả năng phân tích hình ảnh vào ứng dụng của mình một cách dễ dàng.

Azure Computer Vision API

Định nghĩa: Là một dịch vụ thuộc Azure Cognitive Services cung cấp khả năng phân tích hình ảnh và trích xuất thông tin từ hình ảnh.

Chức năng chính:

  • Image Analysis: Trích xuất thông tin từ hình ảnh như nhãn, màu sắc, người, đối tượng, và văn bản.

  • OCR (Optical Character Recognition): Nhận dạng ký tự trong hình ảnh, hỗ trợ nhiều ngôn ngữ.

  • Face API: Nhận diện và phân tích khuôn mặt, bao gồm nhận dạng tuổi, giới tính, cảm xúc.

Azure Custom Vision

Định nghĩa: Cho phép bạn tạo các mô hình AI tùy chỉnh cho Image Classification và Object Detection bằng cách tải lên các bộ dữ liệu riêng và huấn luyện mô hình ngay trên Azure.

Chức năng chính:

  • Image Classification: Tự động phân loại hình ảnh dựa trên nhãn do người dùng định nghĩa.

  • Object Detection: Phát hiện và khoanh vùng các đối tượng trong hình ảnh.

Azure Face API

Định nghĩa: Cung cấp khả năng phát hiện và nhận diện khuôn mặt, phân tích đặc điểm khuôn mặt như tuổi, giới tính, cảm xúc.

Chức năng chính:

  • Face Detection: Phát hiện khuôn mặt trong ảnh và video.

  • Face Verification: Xác minh danh tính dựa trên khuôn mặt.

  • Face Identification: Nhận diện và theo dõi người dựa trên khuôn mặt.

4. Triển khai và ứng dụng

Sử dụng Azure Computer Vision API:

from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from msrest.authentication import CognitiveServicesCredentials

subscription_key = "YOUR_SUBSCRIPTION_KEY"
endpoint = "YOUR_ENDPOINT"

computervision_client = ComputerVisionClient(endpoint, CognitiveServicesCredentials(subscription_key))

image_url = "IMAGE_URL"
analyze_image = computervision_client.analyze_image(image_url)

for tag in analyze_image.tags:
    print(tag.name, tag.confidence)

Sử dụng Azure Custom Vision:

from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient
from msrest.authentication import ApiKeyCredentials

prediction_key = "YOUR_PREDICTION_KEY"
endpoint = "YOUR_ENDPOINT"
project_id = "YOUR_PROJECT_ID"
model_name = "YOUR_MODEL_NAME"

credentials = ApiKeyCredentials(in_headers={"Prediction-key": prediction_key})
predictor = CustomVisionPredictionClient(endpoint, credentials)

image_url = "IMAGE_URL"
results = predictor.classify_image_url(project_id, model_name, image_url)

for prediction in results.predictions:
    print(f"{prediction.tag_name}: {prediction.probability:.2f}")

Phân biệt Azure Cognitive Services, Azure Computer Vision và Azure Custom Vision (Training, Predictive)

1. Azure Cognitive Services

Azure Cognitive Services là một bộ dịch vụ AI được quản lý hoàn toàn, cung cấp bởi Microsoft Azure, cho phép các nhà phát triển thêm các tính năng AI vào ứng dụng của họ mà không cần có kiến thức sâu về AI. Các dịch vụ này bao gồm phân tích văn bản, nhận dạng hình ảnh, xử lý ngôn ngữ tự nhiên, và nhiều hơn nữa.

2. Azure Computer Vision

Azure Computer Vision là một dịch vụ trong bộ Azure Cognitive Services, tập trung vào việc phân tích và trích xuất thông tin từ hình ảnh và video. Các tính năng chính bao gồm:

  • OCR (Optical Character Recognition): Nhận dạng và trích xuất văn bản từ hình ảnh.

  • Image Analysis: Nhận dạng đối tượng, nhãn, và các thuộc tính khác của hình ảnh.

  • Face Detection: Phát hiện và phân tích các khuôn mặt trong hình ảnh.

  • Thumbnail Generation: Tạo các ảnh thu nhỏ từ ảnh gốc.

3. Azure Custom Vision

Azure Custom Vision cho phép bạn xây dựng các mô hình nhận dạng hình ảnh tùy chỉnh theo nhu cầu cụ thể của bạn. Nó có hai thành phần chính:

  • Training: Dùng để tạo và huấn luyện các mô hình AI dựa trên bộ dữ liệu của bạn.

  • Prediction: Dùng để dự đoán và phân loại các hình ảnh mới dựa trên mô hình đã được huấn luyện.

Các bước cần thiết để sử dụng Azure Computer Vision và Azure Custom Vision sau khi tạo Cognitive Services

Azure Computer Vision

  1. Tạo một tài khoản Azure Cognitive Services:

    • Đăng nhập vào Azure Portal.

    • Chọn "Create a resource".

    • Tìm kiếm "Cognitive Services" và làm theo hướng dẫn để tạo tài khoản.

  2. Lấy khóa API và Endpoint:

    • Sau khi tạo tài khoản, truy cập vào nó và lấy khóa API cùng với endpoint.
  3. Sử dụng Azure Computer Vision:

    • Sử dụng các thư viện SDK hoặc REST API của Azure để kết nối và sử dụng các dịch vụ Computer Vision.

Ví dụ Python để sử dụng Computer Vision API:

from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from msrest.authentication import CognitiveServicesCredentials

# Khóa và endpoint
subscription_key = "your_subscription_key"
endpoint = "your_endpoint"

# Khởi tạo khách hàng ComputerVisionClient
computervision_client = ComputerVisionClient(endpoint, CognitiveServicesCredentials(subscription_key))

# URL của hình ảnh để phân tích
remote_image_url = "<https://example.com/image.jpg>"

# Phân tích hình ảnh
analyze_features = ["Description"]
analysis = computervision_client.analyze_image(remote_image_url, analyze_features)

print("Description: ")
for caption in analysis.description.captions:
    print(f"'{caption.text}' with confidence {caption.confidence * 100:.2f}%")

Azure Custom Vision

  1. Tạo Custom Vision Project:

    • Đăng nhập vào Azure Custom Vision portal.

    • Tạo một dự án mới, chọn loại dự án là Classification hoặc Object Detection tùy vào yêu cầu của bạn.

    • Upload các hình ảnh để huấn luyện và gán nhãn chúng.

  2. Huấn luyện mô hình:

    • Sau khi upload hình ảnh và gán nhãn, bắt đầu quá trình huấn luyện mô hình.
  3. Lấy Prediction API key và endpoint:

    • Sau khi huấn luyện xong, lấy API key và endpoint cho dịch vụ Prediction.
  4. Sử dụng mô hình để dự đoán:

    • Sử dụng SDK hoặc REST API để gửi các hình ảnh mới và nhận kết quả dự đoán.

Ví dụ Python để sử dụng Custom Vision API:

from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient
from msrest.authentication import ApiKeyCredentials
import requests
from PIL import Image

# Khóa và endpoint cho dịch vụ Prediction
prediction_key = "your_prediction_key"
endpoint = "your_prediction_endpoint"
project_id = "your_project_id"
published_name = "your_published_iteration_name"

# Khởi tạo khách hàng CustomVisionPredictionClient
prediction_credentials = ApiKeyCredentials(in_headers={"Prediction-key": prediction_key})
predictor = CustomVisionPredictionClient(endpoint, prediction_credentials)

# Hình ảnh để dự đoán
image_path = "path_to_your_image.jpg"

# Dự đoán hình ảnh
with open(image_path, "rb") as image_contents:
    results = predictor.classify_image(project_id, published_name, image_contents.read())

for prediction in results.predictions:
    print(f"'{prediction.tag_name}' with probability {prediction.probability * 100:.2f}%")

Tạo hạ tầng bằng Terraform

Link tham khảo: https://github.com/hashicorp/terraform-provider-azurerm/blob/main/website/docs/r/cognitive_account.html.markdown

Quickstart: Create an Azure AI services resource using Terraform - Azure AI services

Để tạo các tài nguyên Azure Cognitive Services và Custom Vision bằng Terraform, bạn có thể sử dụng cấu hình sau:

provider "azurerm" {
  features {}
}

resource "azurerm_resource_group" "example" {
  name     = "example-resources"
  location = "East US"
}

# Cognitive Services
resource "azurerm_cognitive_account" "example_cognitive_account" {
  name                = "examplecognitiveaccount"
  resource_group_name = azurerm_resource_group.example.name
  location            = azurerm_resource_group.example.location
  kind                = "CognitiveServices"
  sku_name            = "S0"
}

# Custom Vision
resource "azurerm_cognitive_account" "example_cv_training_account" {
  name                = "examplecvtrainaccount"
  resource_group_name = azurerm_resource_group.example.name
  location            = azurerm_resource_group.example.location
  kind                = "CustomVision.Training"
  sku_name            = "F0"
}

resource "azurerm_cognitive_account" "example_cv_prediction_account" {
  name                = "examplecvpredictaccount"
  resource_group_name = azurerm_resource_group.example.name
  location            = azurerm_resource_group.example.location
  kind                = "CustomVision.Prediction"
  sku_name            = "F0"
}

# Computer Vision
resource "azurerm_cognitive_account" "example" {
  name                = "examplecvaccount"
  location            = azurerm_resource_group.example.location
  resource_group_name = azurerm_resource_group.example.name
  kind                = "ComputerVision"

  sku_name = "F0"

  tags = {
    Acceptance = "Test"
  }
}

Code Terraform này sẽ tạo ra tất cả cognitive account cần thiết để cho phần thực hành bên dưới, do đó bạn sẽ chưa destroy resources sau khi apply.

Tham khảo thêm: https://github.com/imcuteani/awesome-terraform-azcognitive/tree/main

Lưu ý: Hiện tại chưa thể tạo Custom Vision project bằng Terraform

Hướng dẫn triển khai Terraform

  1. Cài đặt Terraform:

    • Tải xuống và cài đặt Terraform từ trang chủ của nó terraform.io.
  2. Khởi tạo Terraform:

    • Tạo một thư mục mới và thêm file main.tf với cấu hình trên.

    • Mở terminal và điều hướng đến thư mục đó.

    • Chạy lệnh terraform init để khởi tạo Terraform.

  3. Triển khai cấu hình:

    • Chạy lệnh terraform apply và xác nhận để triển khai cấu hình.

    • Terraform sẽ tạo các tài nguyên cần thiết trên Azure.

Thực hành với Azure Computer Vision và Azure Custom Vision

Tài liệu tham khảo: https://microsoftlearning.github.io/AI-102-AIEngineer/

Face recognize

Tài liệu tham khảo: https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/concept-detecting-faces

https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/quickstarts-sdk/identity-client-library?tabs=windows,visual-studio&pivots=programming-language-python

Sử dụng Computer Vision

Image:

Cài đặt thư viện:

pip install azure-cognitiveservices-vision-computervision
pip install msrest
pip install python-dotenv
pip install pillow

.env

COG_SERVICE_ENDPOINT=your_cognitive_services_endpoint
COG_SERVICE_KEY=your_cognitive_services_key

detect-faces.py

from dotenv import load_dotenv
import os
from PIL import Image, ImageDraw
from matplotlib import pyplot as plt

# Import namespaces
from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
from msrest.authentication import CognitiveServicesCredentials

def main():
    try:
        # Get Configuration Settings
        load_dotenv()
        cog_endpoint = os.getenv('COG_SERVICE_ENDPOINT')
        cog_key = os.getenv('COG_SERVICE_KEY')

        # Authenticate Azure AI Vision client
        client = ComputerVisionClient(
            cog_endpoint,
            CognitiveServicesCredentials(cog_key)
        )

        # Detect faces in an image
        image_file = os.path.join('images','people.jpg')
        AnalyzeFaces(client, image_file)

    except Exception as ex:
        print(ex)

def AnalyzeFaces(client, image_file):
    print('Analyzing', image_file)

    # Specify features to be retrieved (faces)
    features = [VisualFeatureTypes.faces]

    # Get image analysis
    with open(image_file, "rb") as image_stream:
        analysis = client.analyze_image_in_stream(image_stream, features)

    # Draw faces on image
    img = Image.open(image_file)
    draw = ImageDraw.Draw(img)
    print(f"Detected {len(analysis.faces)} faces in the image.")
    for i, face in enumerate(analysis.faces, start=1):
        r = face.face_rectangle
        draw.rectangle(((r.left, r.top), (r.left + r.width, r.top + r.height)), outline='red')
        print(f"Face {i}:")
        print(f"  Rectangle: left={r.left}, top={r.top}, width={r.width}, height={r.height}")
        print(f"  Age: {face.age}")
        print(f"  Gender: {face.gender}")

    # Display the image
    plt.imshow(img)
    plt.show()

if __name__ == "__main__":
    main()

Code này sử dụng dịch vụ Azure Computer Vision để phát hiện các khuôn mặt trong một hình ảnh và vẽ khung chữ nhật xung quanh mỗi khuôn mặt được phát hiện. Dưới đây là chi tiết từng phần của mã:

1. Import các thư viện cần thiết

from dotenv import load_dotenv
import os
from PIL import Image, ImageDraw
from matplotlib import pyplot as plt

# Import namespaces
from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
from msrest.authentication import CognitiveServicesCredentials
  • dotenv: Để tải các biến môi trường từ file .env.

  • os: Để thao tác với hệ điều hành, đặc biệt là để lấy đường dẫn và biến môi trường.

  • PILmatplotlib: Để mở và vẽ trên hình ảnh.

  • azure.cognitiveservices.vision.computervision: Thư viện Azure SDK để làm việc với dịch vụ Computer Vision.

  • msrest.authentication: Để xác thực với dịch vụ Azure bằng cách sử dụng khóa API.

2. Hàmmain

def main():
    try:
        # Get Configuration Settings
        load_dotenv()
        cog_endpoint = os.getenv('COG_SERVICE_ENDPOINT')
        cog_key = os.getenv('COG_SERVICE_KEY')

        # Authenticate Azure AI Vision client
        client = ComputerVisionClient(
            cog_endpoint,
            CognitiveServicesCredentials(cog_key)
        )

        # Detect faces in an image
        image_file = os.path.join('images','people.jpg')
        AnalyzeFaces(client, image_file)

    except Exception as ex:
        print(ex)
  • load_dotenv(): Tải các biến môi trường từ file .env.

  • cog_endpointcog_key: Lấy endpoint và khóa API của dịch vụ Azure Computer Vision từ biến môi trường.

  • ComputerVisionClient: Khởi tạo client để tương tác với dịch vụ Azure Computer Vision.

  • image_file: Đường dẫn đến file hình ảnh sẽ được phân tích.

  • AnalyzeFaces(client, image_file): Gọi hàm AnalyzeFaces để phân tích khuôn mặt trong hình ảnh.

3. HàmAnalyzeFaces

def AnalyzeFaces(client, image_file):
    print('Analyzing', image_file)

    # Specify features to be retrieved (faces)
    features = [VisualFeatureTypes.faces]

    # Get image analysis
    with open(image_file, "rb") as image_stream:
        analysis = client.analyze_image_in_stream(image_stream, features)

    # Draw faces on image
    img = Image.open(image_file)
    draw = ImageDraw.Draw(img)
    print(f"Detected {len(analysis.faces)} faces in the image.")
    for i, face in enumerate(analysis.faces, start=1):
        r = face.face_rectangle
        draw.rectangle(((r.left, r.top), (r.left + r.width, r.top + r.height)), outline='red')
        print(f"Face {i}:")
        print(f"  Rectangle: left={r.left}, top={r.top}, width={r.width}, height={r.height}")
        print(f"  Age: {face.age}")
        print(f"  Gender: {face.gender}")

    # Display the image
    plt.imshow(img)
    plt.show()
  • features = [VisualFeatureTypes.faces]: Chỉ định rằng chúng ta muốn dịch vụ Computer Vision trả về thông tin về khuôn mặt trong hình ảnh.

  • client.analyze_image_in_stream(image_stream, features): Gửi hình ảnh đến dịch vụ Computer Vision để phân tích và lấy thông tin về khuôn mặt.

  • Image.open(image_file): Mở hình ảnh sử dụng PIL.

  • ImageDraw.Draw(img): Tạo một đối tượng để vẽ lên hình ảnh.

  • draw.rectangle(...): Vẽ khung chữ nhật xung quanh mỗi khuôn mặt được phát hiện.

  • plt.imshow(img): Hiển thị hình ảnh với khung chữ nhật được vẽ.

Kết quả:

$ python detect-faces.py

Analyzing images\\people.jpg
Detected 2 faces in the image.
Face 1:
  Rectangle: left=221, top=86, width=124, height=124
  Age: None
  Gender: None
Face 2:
  Rectangle: left=498, top=166, width=111, height=111
  Age: None
  Gender: None

Sử dụng Face API

Tài liệu: https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/overview-identity

.env

COG_SERVICE_ENDPOINT=your_cognitive_services_endpoint
COG_SERVICE_KEY=your_cognitive_services_key

analyze-faces.py

from dotenv import load_dotenv
import os
from PIL import Image, ImageDraw
from matplotlib import pyplot as plt

# Import namespaces
from azure.cognitiveservices.vision.face import FaceClient
from azure.cognitiveservices.vision.face.models import FaceAttributeType
from msrest.authentication import CognitiveServicesCredentials

def main():

    global face_client

    try:
        # Get Configuration Settings
        load_dotenv()
        cog_endpoint = os.getenv('COG_SERVICE_ENDPOINT')
        cog_key = os.getenv('COG_SERVICE_KEY')

        # Authenticate Face client
        credentials = CognitiveServicesCredentials(cog_key)
        face_client = FaceClient(cog_endpoint, credentials)

        # Menu for face functions
        print('1: Detect faces\\nAny other key to quit')
        command = input('Enter a number:')
        if command == '1':
            DetectFaces(os.path.join('images','people.jpg'))

    except Exception as ex:
        print(ex)

def DetectFaces(image_file):
    print('Detecting faces in', image_file)

    # Specify facial features to be retrieved
    features = [FaceAttributeType.occlusion,
             FaceAttributeType.blur,
             FaceAttributeType.glasses]

    # Get faces
    with open(image_file, mode="rb") as image_data:
        detected_faces = face_client.face.detect_with_stream(image=image_data,
                                                                return_face_attributes=features,                     return_face_id=False)

        if len(detected_faces) > 0:
            print(len(detected_faces), 'faces detected.')

            # Prepare image for drawing
            fig = plt.figure(figsize=(8, 6))
            plt.axis('off')
            image = Image.open(image_file)
            draw = ImageDraw.Draw(image)
            color = 'lightgreen'
            face_count = 0

            # Draw and annotate each face
            for face in detected_faces:

                # Get face properties
                face_count += 1
                print('\\nFace number {}'.format(face_count))

                detected_attributes = face.face_attributes.as_dict()
                if 'blur' in detected_attributes:
                    print(' - Blur:')
                    for blur_name in detected_attributes['blur']:
                        print('   - {}: {}'.format(blur_name, detected_attributes['blur'][blur_name]))

                if 'occlusion' in detected_attributes:
                    print(' - Occlusion:')
                    for occlusion_name in detected_attributes['occlusion']:
                        print('   - {}: {}'.format(occlusion_name, detected_attributes['occlusion'][occlusion_name]))

                if 'glasses' in detected_attributes:
                    print(' - Glasses:{}'.format(detected_attributes['glasses']))

                # Draw and annotate face
                r = face.face_rectangle
                bounding_box = ((r.left, r.top), (r.left + r.width, r.top + r.height))
                draw = ImageDraw.Draw(image)
                draw.rectangle(bounding_box, outline=color, width=5)
                annotation = 'Face ID: {}'.format(face.face_id)
                plt.annotate(annotation,(r.left, r.top), backgroundcolor=color)

            # Save annotated image
            plt.imshow(image)
            outputfile = 'detected_faces.jpg'
            fig.savefig(outputfile)

            print('\\nResults saved in', outputfile)

if __name__ == "__main__":
    main()

Giải thích code:

Import thư viện

from dotenv import load_dotenv
import os
from PIL import Image, ImageDraw
from matplotlib import pyplot as plt

# Import namespaces
from azure.cognitiveservices.vision.face import FaceClient
from azure.cognitiveservices.vision.face.models import FaceAttributeType
from msrest.authentication import CognitiveServicesCredentials
  • dotenv: Được sử dụng để tải các biến môi trường từ tệp .env.

  • os: Cung cấp các chức năng liên quan đến hệ điều hành.

  • PIL (Python Imaging Library): Được sử dụng để mở, thao tác và lưu các tệp hình ảnh.

  • matplotlib.pyplot: Được sử dụng để vẽ và hiển thị đồ thị.

  • azure.cognitiveservices.vision.face: Chứa FaceClient để truy cập các dịch vụ khuôn mặt của Azure.

  • msrest.authentication: Cung cấp các thông tin xác thực cần thiết để xác thực với Azure Cognitive Services.

Hàm chính

def main():
    global face_client

    try:
        # Get Configuration Settings
        load_dotenv()
        cog_endpoint = os.getenv('COG_SERVICE_ENDPOINT')
        cog_key = os.getenv('COG_SERVICE_KEY')

        # Authenticate Face client
        credentials = CognitiveServicesCredentials(cog_key)
        face_client = FaceClient(cog_endpoint, credentials)

        # Menu for face functions
        print('1: Detect faces\\\\nAny other key to quit')
        command = input('Enter a number:')
        if command == '1':
            DetectFaces(os.path.join('images','people.jpg'))

    except Exception as ex:
        print(ex)
  1. Tải các biến môi trường: Đoạn mã tải các biến môi trường (endpoint và key của dịch vụ nhận diện khuôn mặt) sử dụng load_dotenv().

  2. Xác thực: Tạo một đối tượng FaceClient sử dụng endpoint và key.

  3. Nhập lệnh từ người dùng: Hiển thị menu và đợi người dùng nhập lệnh. Nếu người dùng nhập 1, chương trình sẽ tiến hành phát hiện khuôn mặt trong hình ảnh được chỉ định.

Hàm DetectFaces

def DetectFaces(image_file):
    print('Detecting faces in', image_file)

    # Specify facial features to be retrieved
    features = [FaceAttributeType.occlusion,
             FaceAttributeType.blur,
             FaceAttributeType.glasses]

    # Get faces
    with open(image_file, mode="rb") as image_data:
        detected_faces = face_client.face.detect_with_stream(image=image_data,
                                                                return_face_attributes=features, return_face_id=False)

        if len(detected_faces) > 0:
            print(len(detected_faces), 'faces detected.')

            # Prepare image for drawing
            fig = plt.figure(figsize=(8, 6))
            plt.axis('off')
            image = Image.open(image_file)
            draw = ImageDraw.Draw(image)
            color = 'lightgreen'
            face_count = 0

            # Draw and annotate each face
            for face in detected_faces:

                # Get face properties
                face_count += 1
                print('\\\\nFace number {}'.format(face_count))

                detected_attributes = face.face_attributes.as_dict()
                if 'blur' in detected_attributes:
                    print(' - Blur:')
                    for blur_name in detected_attributes['blur']:
                        print('   - {}: {}'.format(blur_name, detected_attributes['blur'][blur_name]))

                if 'occlusion' in detected_attributes:
                    print(' - Occlusion:')
                    for occlusion_name in detected_attributes['occlusion']:
                        print('   - {}: {}'.format(occlusion_name, detected_attributes['occlusion'][occlusion_name]))

                if 'glasses' in detected_attributes:
                    print(' - Glasses:{}'.format(detected_attributes['glasses']))

                # Draw and annotate face
                r = face.face_rectangle
                bounding_box = ((r.left, r.top), (r.left + r.width, r.top + r.height))
                draw.rectangle(bounding_box, outline=color, width=5)
                annotation = 'Face ID: {}'.format(face.face_id)
                plt.annotate(annotation,(r.left, r.top), backgroundcolor=color)

            # Save annotated image
            plt.imshow(image)
            outputfile = 'detected_faces.jpg'
            fig.savefig(outputfile)

            print('\\\\nResults saved in', outputfile)
  1. Chỉ định các thuộc tính khuôn mặt: Danh sách features chỉ định các thuộc tính khuôn mặt cần được truy xuất (che khuất, mờ, kính).

  2. Phát hiện khuôn mặt: Đọc tệp hình ảnh và phát hiện khuôn mặt sử dụng phương thức face_client.face.detect_with_stream().

  3. Vẽ và chú thích: Nếu phát hiện được khuôn mặt, nó sẽ vẽ các hình chữ nhật xung quanh mỗi khuôn mặt và chú thích chúng với các thuộc tính phát hiện được.

  4. Lưu kết quả: Hình ảnh đã được chú thích sẽ được hiển thị và lưu lại dưới tên detected_faces.jpg.

Kết quả:

python analyze-faces.py

1: Detect faces
Any other key to quit
Enter a number:1
Detecting faces in images\\people.jpg
2 faces detected.

Face number 1
 - Blur:
   - blur_level: Low
   - value: 0.0
 - Occlusion:
   - forehead_occluded: False
   - eye_occluded: False
   - mouth_occluded: False
 - Glasses:noGlasses

Face number 2
 - Blur:
   - blur_level: Low
   - value: 0.0
 - Occlusion:
   - forehead_occluded: False
   - eye_occluded: False
   - mouth_occluded: False
 - Glasses:readingGlasses

Results saved in detected_faces.jpg

Analyze Images với Azure AI Vision

Tài liệu tham khảo:

https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/quickstarts-sdk/image-analysis-client-library-40?tabs=visual-studio,windows&pivots=programming-language-python

https://microsoftlearning.github.io/AI-102-AIEngineer/Instructions/15-computer-vision.html

https://github.com/Azure-Samples/cognitive-services-python-sdk-samples/blob/master/samples/vision/computer_vision_samples.py

Images:

.env:

COG_SERVICE_ENDPOINT=your_cognitive_services_endpoint
COG_SERVICE_KEY=your_cognitive_services_key

image-analysis.py

from dotenv import load_dotenv
import os
from array import array
from PIL import Image, ImageDraw
import sys
import time
from matplotlib import pyplot as plt
import numpy as np

# Import namespaces
from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
from msrest.authentication import CognitiveServicesCredentials

def main():
    global cv_client

    try:
        # Get Configuration Settings
        load_dotenv()
        cog_endpoint = os.getenv('COG_SERVICE_ENDPOINT')
        cog_key = os.getenv('COG_SERVICE_KEY')

        # Get image
        image_file = 'images/street.jpg'
        if len(sys.argv) > 1:
            image_file = sys.argv[1]

        # Authenticate Azure AI Vision client
        credential = CognitiveServicesCredentials(cog_key) 
        cv_client = ComputerVisionClient(cog_endpoint, credential)

        # Analyze image
        AnalyzeImage(cv_client, image_file)

        # Generate thumbnail
        GetThumbnail(image_file)

    except Exception as ex:
        print(ex)

def AnalyzeImage(cv_client, image_file):
    print('Analyzing', image_file)

    # Specify features to be retrieved
    features = [VisualFeatureTypes.description,
            VisualFeatureTypes.tags,
            VisualFeatureTypes.categories,
            VisualFeatureTypes.brands,
            VisualFeatureTypes.objects,
            VisualFeatureTypes.adult]

    # Get image analysis
    with open(image_file, mode="rb") as image_data:
        analysis = cv_client.analyze_image_in_stream(image_data , features)
    # Get image tags
    if (len(analysis.tags) > 0):
        print("Tags: ")
        for tag in analysis.tags:
            print(" -'{}' (confidence: {:.2f}%)".format(tag.name, tag.confidence * 100))
    # Get image category
    if (len(analysis.categories) > 0):
        print("Categories:")
        landmarks = []
        for category in analysis.categories:
            # Print the category
            print(" -'{}' (confidence: {:.2f}%)".format(category.name, category.score * 100))
            if category.detail:
                # Get landmarks in this category
                if category.detail.landmarks:
                    for landmark in category.detail.landmarks:
                        if landmark not in landmarks:
                            landmarks.append(landmark)

    # If there were landmarks, list them
    if len(landmarks) > 0:
        print("Landmarks:")
        for landmark in landmarks:
            print(" -'{}' (confidence: {:.2f}%)".format(landmark.name, landmark.confidence * 100))
    # Get brands in the image
    if (len(analysis.brands) > 0):
        print("Brands: ")
        for brand in analysis.brands:
            print(" -'{}' (confidence: {:.2f}%)".format(brand.name, brand.confidence * 100))

    # Get objects in the image
    if len(analysis.objects) > 0:
        print("Objects in image:")

        # Prepare image for drawing
        fig = plt.figure(figsize=(8, 8))
        plt.axis('off')
        image = Image.open(image_file)
        draw = ImageDraw.Draw(image)
        color = 'cyan'
        for detected_object in analysis.objects:
            # Print object name
            print(" -{} (confidence: {:.2f}%)".format(detected_object.object_property, detected_object.confidence * 100))

            # Draw object bounding box
            r = detected_object.rectangle
            bounding_box = ((r.x, r.y), (r.x + r.w, r.y + r.h))
            draw.rectangle(bounding_box, outline=color, width=3)
            plt.annotate(detected_object.object_property,(r.x, r.y), backgroundcolor=color)
        # Save annotated image
        plt.imshow(image)
        outputfile = 'objects.jpg'
        fig.savefig(outputfile)
        print('  Results saved in', outputfile)

def GetThumbnail(image_file):
    print('Generating thumbnail')

    # Generate a thumbnail
    with open(image_file, mode="rb") as image_data:
        # Get thumbnail data
        thumbnail_stream = cv_client.generate_thumbnail_in_stream(100, 100, image_data, True)

        # Save thumbnail image
        thumbnail_file_name = 'thumbnail.png'
        with open(thumbnail_file_name, "wb") as thumbnail_file:
            for chunk in thumbnail_stream:
                thumbnail_file.write(chunk)


        print('Thumbnail saved in.', thumbnail_file_name)

if __name__ == "__main__":
    main()

Chúng ta sẽ phân tích và giải thích chi tiết đoạn mã này. Đoạn mã sử dụng dịch vụ Azure Cognitive Services để phân tích hình ảnh và tạo thumbnail cho hình ảnh.

Import thư viện

from dotenv import load_dotenv
import os
from array import array
from PIL import Image, ImageDraw
import sys
import time
from matplotlib import pyplot as plt
import numpy as np

# Import namespaces
from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
from msrest.authentication import CognitiveServicesCredentials
  • dotenv: Được sử dụng để tải các biến môi trường từ tệp .env.

  • os: Cung cấp các chức năng liên quan đến hệ điều hành.

  • array: Module cung cấp một kiểu dữ liệu mảng hiệu quả.

  • PIL (Python Imaging Library): Được sử dụng để mở, thao tác và lưu các tệp hình ảnh.

  • sys: Cung cấp các tham số và hàm cụ thể của hệ thống.

  • time: Module cung cấp các chức năng liên quan đến thời gian.

  • matplotlib.pyplot: Được sử dụng để vẽ và hiển thị đồ thị.

  • numpy: Thư viện hỗ trợ tính toán mảng và ma trận lớn.

  • azure.cognitiveservices.vision.computervision: Chứa ComputerVisionClient để truy cập các dịch vụ nhận diện hình ảnh của Azure.

  • msrest.authentication: Cung cấp các thông tin xác thực cần thiết để xác thực với Azure Cognitive Services.

Hàm chính

def main():
    global cv_client

    try:
        # Get Configuration Settings
        load_dotenv()
        cog_endpoint = os.getenv('COG_SERVICE_ENDPOINT')
        cog_key = os.getenv('COG_SERVICE_KEY')

        # Get image
        image_file = 'images/street.jpg'
        if len(sys.argv) > 1:
            image_file = sys.argv[1]

        # Authenticate Azure AI Vision client
        credential = CognitiveServicesCredentials(cog_key)
        cv_client = ComputerVisionClient(cog_endpoint, credential)

        # Analyze image
        AnalyzeImage(cv_client, image_file)

        # Generate thumbnail
        GetThumbnail(image_file)

    except Exception as ex:
        print(ex)
  1. Tải các biến môi trường: Đoạn mã tải các biến môi trường (endpoint và key của dịch vụ nhận diện hình ảnh) sử dụng load_dotenv().

  2. Lấy hình ảnh: Đoạn mã lấy đường dẫn đến tệp hình ảnh, nếu không có tham số đầu vào thì mặc định là images/street.jpg.

  3. Xác thực: Tạo một đối tượng ComputerVisionClient sử dụng endpoint và key.

  4. Phân tích hình ảnh: Gọi hàm AnalyzeImage để phân tích hình ảnh.

  5. Tạo thumbnail: Gọi hàm GetThumbnail để tạo thumbnail cho hình ảnh.

Hàm AnalyzeImage

def AnalyzeImage(cv_client, image_file):
    print('Analyzing', image_file)

    # Specify features to be retrieved
    features = [VisualFeatureTypes.description,
            VisualFeatureTypes.tags,
            VisualFeatureTypes.categories,
            VisualFeatureTypes.brands,
            VisualFeatureTypes.objects,
            VisualFeatureTypes.adult]

    # Get image analysis
    with open(image_file, mode="rb") as image_data:
        analysis = cv_client.analyze_image_in_stream(image_data , features)
    # Get image tags
    if (len(analysis.tags) > 0):
        print("Tags: ")
        for tag in analysis.tags:
            print(" -'{}' (confidence: {:.2f}%)".format(tag.name, tag.confidence * 100))
    # Get image category
    if (len(analysis.categories) > 0):
        print("Categories:")
        landmarks = []
        for category in analysis.categories:
            # Print the category
            print(" -'{}' (confidence: {:.2f}%)".format(category.name, category.score * 100))
            if category.detail:
                # Get landmarks in this category
                if category.detail.landmarks:
                    for landmark in category.detail.landmarks:
                        if landmark not in landmarks:
                            landmarks.append(landmark)

    # If there were landmarks, list them
    if len(landmarks) > 0:
        print("Landmarks:")
        for landmark in landmarks:
            print(" -'{}' (confidence: {:.2f}%)".format(landmark.name, landmark.confidence * 100))
    # Get brands in the image
    if (len(analysis.brands) > 0):
        print("Brands: ")
        for brand in analysis.brands:
            print(" -'{}' (confidence: {:.2f}%)".format(brand.name, brand.confidence * 100))

    # Get objects in the image
    if len(analysis.objects) > 0):
        print("Objects in image:")

        # Prepare image for drawing
        fig = plt.figure(figsize=(8, 8))
        plt.axis('off')
        image = Image.open(image_file)
        draw = ImageDraw.Draw(image)
        color = 'cyan'
        for detected_object in analysis.objects:
            # Print object name
            print(" -{} (confidence: {:.2f}%)".format(detected_object.object_property, detected_object.confidence * 100))

            # Draw object bounding box
            r = detected_object.rectangle
            bounding_box = ((r.x, r.y), (r.x + r.w, r.y + r.h))
            draw.rectangle(bounding_box, outline=color, width=3)
            plt.annotate(detected_object.object_property,(r.x, r.y), backgroundcolor=color)
        # Save annotated image
        plt.imshow(image)
        outputfile = 'objects.jpg'
        fig.savefig(outputfile)
        print('  Results saved in', outputfile)
  1. Chỉ định các thuộc tính: Danh sách features chỉ định các thuộc tính cần được truy xuất (mô tả, thẻ, danh mục, thương hiệu, đối tượng, nội dung người lớn).

  2. Phân tích hình ảnh: Đọc tệp hình ảnh và phân tích sử dụng phương thức cv_client.analyze_image_in_stream().

  3. Lấy thẻ hình ảnh: Nếu có thẻ, in ra các thẻ cùng độ tin cậy.

  4. Lấy danh mục hình ảnh: Nếu có danh mục, in ra các danh mục cùng độ tin cậy. Nếu có landmarks trong danh mục, thêm chúng vào danh sách landmarks.

  5. Lấy thương hiệu: Nếu có thương hiệu, in ra các thương hiệu cùng độ tin cậy.

  6. Lấy các đối tượng trong hình ảnh: Nếu có đối tượng, in ra các đối tượng cùng độ tin cậy. Vẽ hình chữ nhật xung quanh các đối tượng và chú thích chúng trên hình ảnh. Lưu hình ảnh đã được chú thích dưới tên objects.jpg.

Hàm GetThumbnail

def GetThumbnail(image_file):
    print('Generating thumbnail')

    # Generate a thumbnail
    with open(image_file, mode="rb") as image_data:
        # Get thumbnail data
        thumbnail_stream = cv_client.generate_thumbnail_in_stream(100, 100, image_data, True)

        # Save thumbnail image
        thumbnail_file_name = 'thumbnail.png'
        with open(thumbnail_file_name, "wb") as thumbnail_file:
            for chunk in thumbnail_stream:
                thumbnail_file.write(chunk)

        print('Thumbnail saved in.', thumbnail_file_name)
  1. Tạo thumbnail: Mở tệp hình ảnh và tạo thumbnail kích thước 100x100 pixel sử dụng phương thức cv_client.generate_thumbnail_in_stream().

  2. Lưu thumbnail: Lưu thumbnail dưới tên thumbnail.png.

Kết quả

python image-analysis.py

Analyzing images/street.jpg
Tags: 
 -'outdoor' (confidence: 99.87%)
 -'land vehicle' (confidence: 99.02%)
 -'vehicle' (confidence: 98.89%)
 -'building' (confidence: 98.55%)
 -'road' (confidence: 95.98%)
 -'wheel' (confidence: 95.14%)
 -'street' (confidence: 94.71%)
 -'person' (confidence: 93.01%)
 -'clothing' (confidence: 91.19%)
 -'taxi' (confidence: 90.95%)
 -'car' (confidence: 84.01%)
 -'dog' (confidence: 82.68%)
 -'yellow' (confidence: 77.08%)
 -'walking' (confidence: 74.11%)
 -'city' (confidence: 64.80%)
 -'woman' (confidence: 57.53%)
Categories:
 -'outdoor_' (confidence: 0.39%)
 -'outdoor_road' (confidence: 55.86%)
Objects in image:
 -car (confidence: 72.40%)
 -taxi (confidence: 77.00%)
 -person (confidence: 78.10%)
 -dog (confidence: 54.40%)
  Results saved in objects.jpg
Generating thumbnail
Thumbnail saved in. thumbnail.png

thumbnal.png

objects.jpg

Classify Images với Azure AI Custom Vision

https://microsoftlearning.github.io/AI-102-AIEngineer/Instructions/17-image-classification.html

Tạo một Custom Vision AI project tại https://customvision.ai

Upload ảnh và đánh tag ảnh, ở đây sẽ upload các ảnh: banana, orange và apple. Sau đó nhấn vào button Train, chọn Quick train và đợi train xong thì thực hiện testing.

Code tạo training:

pip install azure-cognitiveservices-vision-customvision

.env


PredictionEndpoint=YOUR_PREDICTION_ENDPOINT
PredictionKey=YOUR_PREDICTION_KEY
ProjectID=YOUR_PROJECT_ID

train-classifier.py

from azure.cognitiveservices.vision.customvision.training import CustomVisionTrainingClient
from azure.cognitiveservices.vision.customvision.training.models import ImageFileCreateBatch, ImageFileCreateEntry, Region
from msrest.authentication import ApiKeyCredentials
import time
import os

def main():
    from dotenv import load_dotenv
    global training_client
    global custom_vision_project

    try:
        # Get Configuration Settings
        load_dotenv()
        training_endpoint = os.getenv('TrainingEndpoint')
        training_key = os.getenv('TrainingKey')
        project_id = os.getenv('ProjectID')

        # Authenticate a client for the training API
        credentials = ApiKeyCredentials(in_headers={"Training-key": training_key})
        training_client = CustomVisionTrainingClient(training_endpoint, credentials)

        # Get the Custom Vision project
        custom_vision_project = training_client.get_project(project_id)

        # Upload and tag images
        Upload_Images('training-images')

        # Train the model
        Train_Model()

    except Exception as ex:
        print(ex)

def Upload_Images(folder):
    print("Uploading images...")
    tags = training_client.get_tags(custom_vision_project.id)
    for tag in tags:
        print(tag.name)
        for image in os.listdir(os.path.join(folder,tag.name)):
            image_data = open(os.path.join(folder,tag.name,image), "rb").read()
            training_client.create_images_from_data(custom_vision_project.id, image_data, [tag.id])

def Train_Model():
    print("Training ...")
    iteration = training_client.train_project(custom_vision_project.id)
    while (iteration.status != "Completed"):
        iteration = training_client.get_iteration(custom_vision_project.id, iteration.id)
        print (iteration.status, '...')
        time.sleep(5)
    print ("Model trained!")

if __name__ == "__main__":
    main()

Giải thích code training:

  1. Nhập các thư viện cần thiết: Đầu tiên, mã này nhập các thư viện cần thiết từ Azure SDK và Python chuẩn.

  2. Hàmmain(): Hàm này là điểm bắt đầu của chương trình. Nó đọc các biến môi trường từ file .env, tạo một client cho API huấn luyện Custom Vision, lấy thông tin về dự án Custom Vision, tải lên và gắn thẻ hình ảnh, và cuối cùng là huấn luyện mô hình.

  3. HàmUpload_Images(folder): Hàm này tải lên và gắn thẻ hình ảnh. Nó lấy danh sách các thẻ từ dự án Custom Vision, sau đó duyệt qua mỗi thẻ và tải lên tất cả các hình ảnh tương ứng từ thư mục được chỉ định.

  4. HàmTrain_Model(): Hàm này huấn luyện mô hình. Nó bắt đầu một vòng lặp huấn luyện và chờ đợi cho đến khi trạng thái huấn luyện hoàn thành.

Sau khi publish model, thì có thể thực hiện testing:

.env:


PredictionEndpoint=YOUR_PREDICTION_ENDPOINT
PredictionKey=YOUR_PREDICTION_KEY
ProjectID=YOUR_PROJECT_ID
ModelName=fruit-classifier

test-classifier.py

from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient
from msrest.authentication import ApiKeyCredentials
import os

def main():
    from dotenv import load_dotenv

    try:
        # Get Configuration Settings
        load_dotenv()
        prediction_endpoint = os.getenv('PredictionEndpoint')
        prediction_key = os.getenv('PredictionKey')
        project_id = os.getenv('ProjectID')
        model_name = os.getenv('ModelName')

        # Authenticate a client for the training API
        credentials = ApiKeyCredentials(in_headers={"Prediction-key": prediction_key})
        prediction_client = CustomVisionPredictionClient(endpoint=prediction_endpoint, credentials=credentials)

        # Classify test images
        for image in os.listdir('test-images'):
            image_data = open(os.path.join('test-images',image), "rb").read()
            results = prediction_client.classify_image(project_id, model_name, image_data)

            # Loop over each label prediction and print any with probability > 50%
            for prediction in results.predictions:
                if prediction.probability > 0.5:
                    print(image, ': {} ({:.0%})'.format(prediction.tag_name, prediction.probability))
    except Exception as ex:
        print(ex)

if __name__ == "__main__":
    main()

Giải thích code testing:

  1. Nhập các thư viện cần thiết: Đầu tiên, mã này nhập các thư viện cần thiết từ Azure SDK và Python chuẩn.

  2. Hàmmain(): Hàm này là điểm bắt đầu của chương trình. Nó đọc các biến môi trường từ file .env, tạo một client cho API dự đoán Custom Vision, sau đó dự đoán nhãn của các hình ảnh kiểm tra.

  3. Hàmmain() chi tiết:

    • Đọc các biến môi trường từ file .env bằng load_dotenv().

    • Tạo một client cho API dự đoán Custom Vision bằng cách sử dụng ApiKeyCredentialsCustomVisionPredictionClient.

    • Duyệt qua tất cả các hình ảnh trong thư mục 'test-images', mở từng hình ảnh và đọc dữ liệu của nó.

    • Sử dụng client dự đoán để phân loại hình ảnh bằng cách gọi classify_image().

    • Duyệt qua tất cả các dự đoán và in ra những dự đoán có xác suất lớn hơn 50%.

Kết quả testing:

python test-classifier.py

IMG_TEST_1.jpg : apple (100%)
IMG_TEST_2.jpg : banana (100%)
IMG_TEST_3.jpg : orange (100%)

Detect Objects trong ảnh với Custom Vision

https://microsoftlearning.github.io/AI-102-AIEngineer/Instructions/18-object-detection.html

Tạo project tại https://customvision.ai

  • Name: Detect Fruit

  • Description: Object detection for fruit.

  • Resource: examplecvtrainaccount

  • Project Types: Object Detection

  • Domains: General

Code load ảnh train lên project:

.env

TrainingEndpoint=https:<endpoint>
TrainingKey=<key>
ProjectID=<project-id>

train-detector.py

from azure.cognitiveservices.vision.customvision.training import CustomVisionTrainingClient
from azure.cognitiveservices.vision.customvision.training.models import ImageFileCreateBatch, ImageFileCreateEntry, Region
from msrest.authentication import ApiKeyCredentials
import time
import json
import os

def main():
    from dotenv import load_dotenv
    global training_client
    global custom_vision_project

    try:
        # Get Configuration Settings
        load_dotenv()
        training_endpoint = os.getenv('TrainingEndpoint')
        training_key = os.getenv('TrainingKey')
        project_id = os.getenv('ProjectID')

        # Authenticate a client for the training API
        credentials = ApiKeyCredentials(in_headers={"Training-key": training_key})
        training_client = CustomVisionTrainingClient(training_endpoint, credentials)

        # Get the Custom Vision project
        custom_vision_project = training_client.get_project(project_id)

        # Upload and tag images
        Upload_Images('images')
    except Exception as ex:
        print(ex)

def Upload_Images(folder):
    print("Uploading images...")

    # Get the tags defined in the project
    tags = training_client.get_tags(custom_vision_project.id)

    # Create a list of images with tagged regions
    tagged_images_with_regions = []

    # Get the images and tagged regions from the JSON file
    with open('tagged-images.json', 'r') as json_file:
        tagged_images = json.load(json_file)
        for image in tagged_images['files']:
            # Get the filename
            file = image['filename']
            # Get the tagged regions
            regions = []
            for tag in image['tags']:
                tag_name = tag['tag']
                # Look up the tag ID for this tag name
                tag_id = next(t for t in tags if t.name == tag_name).id
                # Add a region for this tag using the coordinates and dimensions in the JSON
                regions.append(Region(tag_id=tag_id, left=tag['left'],top=tag['top'],width=tag['width'],height=tag['height']))
            # Add the image and its regions to the list
            with open(os.path.join(folder,file), mode="rb") as image_data:
                tagged_images_with_regions.append(ImageFileCreateEntry(name=file, contents=image_data.read(), regions=regions))

    # Upload the list of images as a batch
    upload_result = training_client.create_images_from_files(custom_vision_project.id, ImageFileCreateBatch(images=tagged_images_with_regions))
    # Check for failure
    if not upload_result.is_batch_successful:
        print("Image batch upload failed.")
        for image in upload_result.images:
            print("Image status: ", image.status)
    else:
        print("Images uploaded.")

if __name__ == "__main__":
    main()
  1. Nhập các thư viện cần thiết: Đầu tiên, mã này nhập các thư viện cần thiết từ Azure SDK và Python chuẩn.

  2. Hàmmain(): Hàm này là điểm bắt đầu của chương trình. Nó đọc các biến môi trường từ file .env, tạo một client cho API huấn luyện Custom Vision, lấy thông tin về dự án Custom Vision, sau đó tải lên và gắn thẻ hình ảnh.

  3. HàmUpload_Images(folder): Hàm này tải lên và gắn thẻ hình ảnh. Nó lấy danh sách các thẻ từ dự án Custom Vision, sau đó đọc thông tin về hình ảnh và vùng được gắn thẻ từ file JSON. Mỗi hình ảnh và các vùng tương ứng của nó được thêm vào danh sách. Cuối cùng, nó tải lên toàn bộ danh sách hình ảnh dưới dạng một batch.

Lên project management console, nhấn Train, sau đó publish project.

Test model:

ảnh test:

.env


PredictionEndpoint=YOUR_PREDICTION_ENDPOINT
PredictionKey=YOUR_PREDICTION_KEY
ProjectID=YOUR_PROJECT_ID
ModelName=fruit-detector

test-detector.py

from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient
from msrest.authentication import ApiKeyCredentials
from matplotlib import pyplot as plt
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import os

def main():
    from dotenv import load_dotenv

    try:
        # Get Configuration Settings
        load_dotenv()
        prediction_endpoint = os.getenv('PredictionEndpoint')
        prediction_key = os.getenv('PredictionKey')
        project_id = os.getenv('ProjectID')
        model_name = os.getenv('ModelName')

        # Authenticate a client for the training API
        credentials = ApiKeyCredentials(in_headers={"Prediction-key": prediction_key})
        prediction_client = CustomVisionPredictionClient(endpoint=prediction_endpoint, credentials=credentials)

        # Load image and get height, width and channels
        image_file = 'produce.jpg'
        print('Detecting objects in', image_file)
        image = Image.open(image_file)
        h, w, ch = np.array(image).shape

        # Detect objects in the test image
        with open(image_file, mode="rb") as image_data:
            results = prediction_client.detect_image(project_id, model_name, image_data)

        # Create a figure for the results
        fig = plt.figure(figsize=(8, 8))
        plt.axis('off')

        # Display the image with boxes around each detected object
        draw = ImageDraw.Draw(image)
        lineWidth = int(w/100)
        color = 'magenta'
        for prediction in results.predictions:
            # Only show objects with a > 50% probability
            if (prediction.probability*100) > 50:
                # Box coordinates and dimensions are proportional - convert to absolutes
                left = prediction.bounding_box.left * w 
                top = prediction.bounding_box.top * h 
                height = prediction.bounding_box.height * h
                width =  prediction.bounding_box.width * w
                # Draw the box
                points = ((left,top), (left+width,top), (left+width,top+height), (left,top+height),(left,top))
                draw.line(points, fill=color, width=lineWidth)
                # Add the tag name and probability
                plt.annotate(prediction.tag_name + ": {0:.2f}%".format(prediction.probability * 100),(left,top), backgroundcolor=color)
        plt.imshow(image)
        outputfile = 'output.jpg'
        fig.savefig(outputfile)
        print('Results saved in ', outputfile)
    except Exception as ex:
        print(ex)

if __name__ == "__main__":
    main()

Đây là một đoạn mã Python sử dụng Azure Custom Vision để dự đoán các đối tượng trong hình ảnh và vẽ các hộp giới hạn xung quanh chúng.

  1. Nhập các thư viện cần thiết: Đầu tiên, mã này nhập các thư viện cần thiết từ Azure SDK, Matplotlib, PIL và Python chuẩn.

  2. Hàmmain(): Hàm này là điểm bắt đầu của chương trình. Nó đọc các biến môi trường từ file .env, tạo một client cho API dự đoán Custom Vision, sau đó dự đoán các đối tượng trong hình ảnh và vẽ các hộp giới hạn xung quanh chúng.

  3. Hàmmain() chi tiết:

    • Đọc các biến môi trường từ file .env bằng load_dotenv().

    • Tạo một client cho API dự đoán Custom Vision bằng cách sử dụng ApiKeyCredentialsCustomVisionPredictionClient.

    • Mở hình ảnh và lấy kích thước của nó.

    • Dự đoán các đối tượng trong hình ảnh bằng cách gọi detect_image().

    • Vẽ các hộp giới hạn xung quanh mỗi đối tượng được dự đoán và thêm tên và xác suất của nó vào hình ảnh.

    • Lưu hình ảnh kết quả.

Kết quả

python test-detector.py

Detecting objects in produce.jpg
Results saved in  output.jpg

Đọc chữ trong ảnh (OCR)

https://microsoftlearning.github.io/AI-102-AIEngineer/Instructions/20-ocr.html

Code

read-text.py

from dotenv import load_dotenv
import os
import time
from PIL import Image, ImageDraw
from matplotlib import pyplot as plt

# import namespaces
from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import OperationStatusCodes
from msrest.authentication import CognitiveServicesCredentials

def main():

    global cv_client

    try:
        # Get Configuration Settings
        load_dotenv()
        cog_endpoint = os.getenv('COG_SERVICE_ENDPOINT')
        cog_key = os.getenv('COG_SERVICE_KEY')

        # Authenticate Azure AI Vision client
        credential = CognitiveServicesCredentials(cog_key) 
        cv_client = ComputerVisionClient(cog_endpoint, credential)

        # Menu for text reading functions
        print('1: Use Read API for image\\n2: Use Read API for document\\n3: Read handwriting\\nAny other key to quit')
        command = input('Enter a number:')
        if command == '1':
            image_file = os.path.join('images','Lincoln.jpg')
            GetTextRead(image_file)
        elif command =='2':
            image_file = os.path.join('images','Rome.pdf')
            GetTextRead(image_file)
        elif command =='3':
            image_file = os.path.join('images','Note.jpg')
            GetTextRead(image_file)

        # Use Read API to read text in image
        with open(image_file, mode="rb") as image_data:
            read_op = cv_client.read_in_stream(image_data, raw=True)

            # Get the async operation ID so we can check for the results
            operation_location = read_op.headers["Operation-Location"]
            operation_id = operation_location.split("/")[-1]

            # Wait for the asynchronous operation to complete
            while True:
                read_results = cv_client.get_read_result(operation_id)
                if read_results.status not in [OperationStatusCodes.running, OperationStatusCodes.not_started]:
                    break
                time.sleep(1)

            # If the operation was successfully, process the text line by line
            if read_results.status == OperationStatusCodes.succeeded:
                for page in read_results.analyze_result.read_results:
                    for line in page.lines:
                        print(line.text)
                        # Uncomment the following line if you'd like to see the bounding box 
                        print(line.bounding_box)


    except Exception as ex:
        print(ex)

def GetTextRead(image_file):
    print('Reading text in {}\\n'.format(image_file))

if __name__ == "__main__":
    main()

Đây là một đoạn mã Python sử dụng Azure Computer Vision để đọc văn bản từ hình ảnh.

  1. Nhập các thư viện cần thiết: Đầu tiên, mã này nhập các thư viện cần thiết từ Azure SDK, PIL, Matplotlib và Python chuẩn.

  2. Hàmmain(): Hàm này là điểm bắt đầu của chương trình. Nó đọc các biến môi trường từ file .env, tạo một client cho API Computer Vision, sau đó đọc văn bản từ hình ảnh dựa trên lựa chọn của người dùng.

  3. Hàmmain() chi tiết:

    • Đọc các biến môi trường từ file .env bằng load_dotenv().

    • Tạo một client cho API Computer Vision bằng cách sử dụng CognitiveServicesCredentialsComputerVisionClient.

    • Hiển thị menu cho người dùng và đọc lựa chọn của họ.

    • Mở hình ảnh tương ứng với lựa chọn của người dùng và đọc dữ liệu của nó.

    • Sử dụng client để đọc văn bản từ hình ảnh bằng cách gọi read_in_stream().

    • Chờ cho đến khi hoạt động bất đồng bộ hoàn thành.

    • Nếu hoạt động thành công, xử lý văn bản từng dòng một.

  4. HàmGetTextRead(image_file): Hàm này chỉ đơn giản là in ra thông báo rằng nó đang đọc văn bản trong hình ảnh được chỉ định.

.env

COG_SERVICE_ENDPOINT=your_cognitive_services_endpoint
COG_SERVICE_KEY=your_cognitive_services_key

Kết quả:

$ python read-text.py
1: Use Read API for image
2: Use Read API for document
3: Read handwriting
Any other key to quit
Enter a number:2
Reading text in images\\Rome.pdf

Margie’s Travel presents…
[1.0169, 1.0754, 2.8885, 1.0754, 2.8885, 1.2321, 1.0169, 1.2321]
Rome
[1.0463, 1.4214, 2.1118, 1.4214, 2.1118, 1.7454, 1.0463, 1.7454]
The historic center of the city is a UNESCO World
[1.0035, 2.0644, 4.0529, 2.0644, 4.0529, 2.1942, 1.0035, 2.1942]
Heritage Site. With wonderful palaces, thousand-year-old
[1.0114, 2.2246, 4.501, 2.2246, 4.501, 2.3542, 1.0114, 2.3542]
churches, grand Romantic ruins, opulent monuments,
[1.0057, 2.3862, 4.2798, 2.3862, 4.2798, 2.5142, 1.0057, 2.5142]
ornate statues and graceful fountains, Rome has an
[1.0049, 2.5446, 4.1758, 2.5446, 4.1758, 2.6742, 1.0049, 2.6742]
immensely rich historical heritage and cosmopolitan
[1.0095, 2.7062, 4.17, 2.7062, 4.17, 2.8342, 1.0095, 2.8342]
atmosphere, making it one of Europe's and the world's
[1.0053, 2.8629, 4.3314, 2.8629, 4.3314, 2.9925, 1.0053, 2.9925]
most visited, famous, influential, and beautiful capitals.
[1.0095, 3.0229, 4.3373, 3.0229, 4.3373, 3.151, 1.0095, 3.151]
Today, Rome has a growing nightlife scene and is also
[1.0035, 3.1829, 4.3591, 3.1829, 4.3591, 3.3125, 1.0035, 3.3125]
seen as a shopping heaven, being regarded as one of
[1.0046, 3.3433, 4.3207, 3.3433, 4.3207, 3.4729, 1.0046, 3.4729]
the fashion capitals of the world.
[1.0028, 3.5033, 2.9704, 3.5033, 2.9704, 3.6314, 1.0028, 3.6314]
Mostly popular for:
[1.0102, 4.4617, 2.2413, 4.4617, 2.2413, 4.5913, 1.0102, 4.5913]
Family & Kids, Arts & Culture, Historical, Leisure,
[1.05, 4.62, 4.0321, 4.62, 4.0321, 4.7496, 1.05, 4.7496]
Outdoors
[1.007, 4.7798, 1.5638, 4.7798, 1.5638, 4.8822, 1.007, 4.8822]
Best time to visit:
[1.0104, 5.1016, 2.1419, 5.1016, 2.1419, 5.2022, 1.0104, 5.2022]
Jun-Sep · Avg. 1.9 in precip · Avg. H 83°F · L 66°F
[1.0424, 5.26, 4.15, 5.26, 4.15, 5.3896, 1.0424, 5.3896]
Book your trip now at www.margiestravel.com
[2.8102, 6.0567, 5.6918, 6.0567, 5.6918, 6.1881, 2.8102, 6.1881]

$ python read-text.py
1: Use Read API for image
2: Use Read API for document
3: Read handwriting
Any other key to quit
Enter a number:1
Reading text in images\\Lincoln.jpg

IN THIS TEMPLE
[325.0, 171.0, 478.0, 169.0, 478.0, 184.0, 325.0, 186.0]
AS IN THE HEARTS OF THE PEOPLE
[241.0, 194.0, 563.0, 187.0, 564.0, 204.0, 241.0, 210.0]
FOR WHOM HE SAVED THE UNION
[237.0, 214.0, 567.0, 209.0, 568.0, 224.0, 237.0, 230.0]
THE MEMORY OF ABRAHAM LINCOLN
[226.0, 235.0, 577.0, 229.0, 577.0, 246.0, 226.0, 253.0]
IS ENSHRINED FOREVER
[287.0, 255.0, 516.0, 252.0, 516.0, 268.0, 287.0, 272.0]

$ python read-text.py
1: Use Read API for image
2: Use Read API for document
3: Read handwriting
Any other key to quit
Enter a number:3
Reading text in images\\Note.jpg

Shopping List
[231.0, 142.0, 690.0, 139.0, 691.0, 234.0, 231.0, 236.0]
Non-fat milk
[150.0, 305.0, 630.0, 301.0, 631.0, 374.0, 151.0, 377.0]
Bread
[141.0, 400.0, 385.0, 396.0, 386.0, 473.0, 143.0, 478.0]
Eggs
[144.0, 522.0, 339.0, 519.0, 344.0, 594.0, 147.0, 595.0]

Dọn dẹp tài nguyên

Bài tập

So sánh Image Classification và Object Detection, cho ví dụ ứng dụng.

1. Image Classification

Image Classification là một hình thức của computer vision dựa trên machine learning, trong đó một mô hình được huấn luyện để phân loại hình ảnh dựa trên chủ đề chính mà chúng chứa. Ví dụ, nếu bạn có một bộ hình ảnh của các loài chó và mèo, bạn có thể huấn luyện một mô hình để phân biệt giữa chó và mèo.

Ứng dụng của Image Classification

  • Phân loại sản phẩm: Trong ngành bán lẻ, Image Classification có thể được sử dụng để tự động phân loại sản phẩm dựa trên hình ảnh của chúng.

  • Phát hiện bệnh: Trong y tế, Image Classification có thể được sử dụng để phân loại các hình ảnh y tế, như hình ảnh X-quang hoặc MRI, để phát hiện các dấu hiệu của bệnh.

2. Object Detection

Object Detection cũng phân loại các đối tượng trong hình ảnh, nhưng nó còn trả về tọa độ của hộp giới hạn cho mỗi đối tượng tìm thấy trong hình ảnh. Ví dụ, nếu một hình ảnh chứa một con chó, một con mèo và một người, thì hoạt động phát hiện đối tượng sẽ liệt kê những đối tượng đó cùng với tọa độ của chúng trong hình ảnh¹.

Ứng dụng của Object Detection

  • Phát hiện và đếm đối tượng: Trong ngành công nghiệp, Object Detection có thể được sử dụng để phát hiện và đếm số lượng các đối tượng trong một hình ảnh, như số lượng sản phẩm trên một dây chuyền sản xuất.

  • Phát hiện khuôn mặt: Trong lĩnh vực an ninh, Object Detection có thể được sử dụng để phát hiện khuôn mặt trong hình ảnh hoặc video.