في هذه المقالة، ستتعلم كيفية استخدام Open Neural Network Exchange (ONNX) لإجراء تنبؤات على نماذج رؤية الكمبيوتر التي تم إنشاؤها من التعلم الآلي التلقائي (AutoML) في Azure التعلم الآلي.
لاستخدام ONNX في التنبؤات، فأنت بحاجة إلى:
تنزيل ملفات نموذج ONNX من تشغيل تدريب AutoML.
فهم المدخلات والمخرجات في نموذج ONNX.
قم بإجراء معالجة مسبقة لبياناتك بحيث تكون بالتنسيق المطلوب لإدخال الصور.
الاستنتاج باستخدام «وقت تشغيل» ONNX في Python.
تصور التنبؤات لمهام الكشف عن العناصر وتجزئة المثيل.
ONNX هو معيار مفتوح لنماذج التعلم الآلي والتعلم العميق. ويتيح استيراد النموذج وتصديره (إمكانية التشغيل التفاعلي) عبر أطر عمل الذكاء الاصطناعي الشائعة. للحصول على مزيد من التفاصيل، استكشف مشروع ONNX GitHub.
ONNX Runtime هو مشروع مفتوح المصدر يدعم الاستنتاج عبر النظام الأساسي. يوفر «وقت تشغيل» ONNX واجهات APIs عبر لغات البرمجة (بما في ذلك Python، و C++، و C#، وC، و Java، و JavaScript). يمكنك استخدام «واجهات برمجة التطبيقات» هذه لإجراء الاستنتاج على صور الإدخال. بعد توافر النموذج الذي تم تصديره إلى تنسيق ONNX، يمكنك استخدام «واجهات برمجة التطبيقات» في أي لغة برمجة يحتاجها مشروعك.
في هذا الدليل، ستتعلم كيفية استخدام واجهات برمجة تطبيقات Python لوقت تشغيل ONNX لإجراء تنبؤات على الصور لمهام الرؤية الشائعة. يمكنك استخدام النماذج المُصدّرة لـ ONNX عبر اللغات.
تثبيت حزمة onnxruntime. تم اختبار الأساليب الواردة في هذه المقالة بالإصدارات من 1.3.0 إلى 1.8.0.
تنزيل ملفات نموذج ONNX
يمكنك تنزيل ملفات نموذج ONNX من عمليات تشغيل AutoML باستخدام «واجهة مستخدم» استوديو Azure Machine Learning أو Azure Machine Learning Python SDK. نوصي بتنزيلها عبر الـ SDK باسم التجربة ومُعرّف التشغيل الأصلي.
Azure Machine Learning Studio
في استوديو Azure Machine Learning، انتقل إلى تجربتك باستخدام الارتباط التشعبي إلى التجربة التي تم إنشاؤها في دفتر ملاحظات التدريب، أو بتحديد اسم التجربة في علامة التبويب «التجارب» ضمن «الأصول». ثم حدّد أفضل تشغيل فرعي.
ضمن أفضل تشغيل فرعي، انتقل إلى Outputs+logs>train_artifacts. استخدم الزر «تنزيل» لتنزيل الملفات التالية يدويًا:
labels.json: ملف يحتوي على جميع الفئات أو التسميات في مجموعة بيانات التدريب.
model.onnx: نموذجًا بتنسيق ONNX.
احفظ ملفات النموذج التي تم تنزيلها في الدليل. يستخدم المثال الوارد في هذه المقالة الدليل ./automl_models.
Azure Machine Learning Python SDK
باستخدام SDK، يمكنك تحديد أفضل تشغيل فرعي (حسب المقياس الأساسي) باسم التجربة ومُعرّف التشغيل الأصلي. ثم، يمكنك تنزيل ملفات labels.json و model.onnx.
تُرجِع التعليمات البرمجية التالية أفضل تشغيل فرعي استنادًا إلى المقياس الأساسي المعني.
from azure.identity import DefaultAzureCredential
from azure.ai.ml import MLClient
mlflow_client = MlflowClient()
credential = DefaultAzureCredential()
ml_client = None
try:
ml_client = MLClient.from_config(credential)
except Exception as ex:
print(ex)
# Enter details of your Azure Machine Learning workspace
subscription_id = ''
resource_group = ''
workspace_name = ''
ml_client = MLClient(credential, subscription_id, resource_group, workspace_name)
import mlflow
from mlflow.tracking.client import MlflowClient
# Obtain the tracking URL from MLClient
MLFLOW_TRACKING_URI = ml_client.workspaces.get(
name=ml_client.workspace_name
).mlflow_tracking_uri
mlflow.set_tracking_uri(MLFLOW_TRACKING_URI)
# Specify the job name
job_name = ''
# Get the parent run
mlflow_parent_run = mlflow_client.get_run(job_name)
best_child_run_id = mlflow_parent_run.data.tags['automl_best_child_run_id']
# get the best child run
best_run = mlflow_client.get_run(best_child_run_id)
قم بتنزيل ملف labels.json، الذي يحتوي على جميع الفئات والتسميات في مجموعة بيانات التدريب.
local_dir = './automl_models'
if not os.path.exists(local_dir):
os.mkdir(local_dir)
labels_file = mlflow_client.download_artifacts(
best_run.info.run_id, 'train_artifacts/labels.json', local_dir
)
في حالة الاستدلال الدفعي للكشف عن العنصر وتجزئة المثيل باستخدام نماذج ONNX، راجع قسم إنشاء النموذج لتسجيل الدفعات.
إنشاء نموذج لتسجيل الدُفعات
بشكل افتراضي، يدعم AutoML للصور تسجيل الدُفعات للتصنيف. لكن نماذج ONNX لاكتشاف العنصر وتجزئة المثيل لا تدعم استنتاج المجموعة. في حالة استنتاج الدفعات للكشف عن العناصر وتجزئة المثيل، استخدم الإجراء التالي لإنشاء نموذج ONNX بحجم الدُفعة المطلوب. لا تعمل النماذج التي تم إنشاؤها بحجم معين لدفعة ما في أحجام الدفعات الأخرى.
قم بتنزيل ملف بيئة conda وإنشاء عنصر بيئة لاستخدامه مع مهمة الأمر.
# Download conda file and define the environment
conda_file = mlflow_client.download_artifacts(
best_run.info.run_id, "outputs/conda_env_v_1_0_0.yml", local_dir
)
from azure.ai.ml.entities import Environment
env = Environment(
name="automl-images-env-onnx",
description="environment for automl images ONNX batch model generation",
image="mcr.microsoft.com/azureml/openmpi4.1.0-cuda11.1-cudnn8-ubuntu18.04",
conda_file=conda_file,
)
استخدم الوسيطات التالية الخاصة بالنموذج لإرسال البرنامج النصي. لمزيد من التفاصيل حول الوسيطات، راجع المعلمات الفائقة المحددة للنموذج وللإشارة إلى أسماء نماذج الكشف عن الكائنات المدعومة ، راجع قسم تصميم النموذج المدعوم.
للحصول على قيم الوسيطة اللازمة لإنشاء نموذج تسجيل الدفعات، راجع البرامج النصية لتسجيل النقاط التي تم إنشاؤها ضمن مجلد المخرجات الخاص بتشغيل تدريب AutoML. استخدم قيم المعلمات الفائقة المتوفرة في متغير إعدادات النموذج داخل ملف التسجيل للحصول على أفضل تشغيل فرعي.
لتصنيف الصور متعدد الفئات، يدعم نموذج ONNX الذي تم إنشاؤه أفضل تشغيل فرعي لتسجيل الدفعات بشكل افتراضي. لذلك، لا توجد وسيطات خاصة بالنموذج مطلوبة لنوع المهمة ويمكنك التخطي إلى قسم تحميل التسميات وملفات نموذج ONNX.
لتصنيف الصور متعدد المسميات، يدعم نموذج ONNX الذي تم إنشاؤه أفضل تشغيل فرعي لتسجيل الدفعات بشكل افتراضي. لذلك، لا توجد وسيطات خاصة بالنموذج مطلوبة لنوع المهمة ويمكنك التخطي إلى قسم تحميل التسميات وملفات نموذج ONNX.
inputs = {'model_name': 'fasterrcnn_resnet34_fpn', # enter the faster rcnn or retinanet model name
'batch_size': 8, # enter the batch size of your choice
'height_onnx': 600, # enter the height of input to ONNX model
'width_onnx': 800, # enter the width of input to ONNX model
'job_name': job_name,
'task_type': 'image-object-detection',
'min_size': 600, # minimum size of the image to be rescaled before feeding it to the backbone
'max_size': 1333, # maximum size of the image to be rescaled before feeding it to the backbone
'box_score_thresh': 0.3, # threshold to return proposals with a classification score > box_score_thresh
'box_nms_thresh': 0.5, # NMS threshold for the prediction head
'box_detections_per_img': 100 # maximum number of detections per image, for all classes
}
inputs = {'model_name': 'yolov5', # enter the yolo model name
'batch_size': 8, # enter the batch size of your choice
'height_onnx': 640, # enter the height of input to ONNX model
'width_onnx': 640, # enter the width of input to ONNX model
'job_name': job_name,
'task_type': 'image-object-detection',
'img_size': 640, # image size for inference
'model_size': 'small', # size of the yolo model
'box_score_thresh': 0.1, # threshold to return proposals with a classification score > box_score_thresh
'box_iou_thresh': 0.5
}
inputs = {'model_name': 'maskrcnn_resnet50_fpn', # enter the maskrcnn model name
'batch_size': 8, # enter the batch size of your choice
'height_onnx': 600, # enter the height of input to ONNX model
'width_onnx': 800, # enter the width of input to ONNX model
'job_name': job_name,
'task_type': 'image-instance-segmentation',
'min_size': 600, # minimum size of the image to be rescaled before feeding it to the backbone
'max_size': 1333, # maximum size of the image to be rescaled before feeding it to the backbone
'box_score_thresh': 0.3, # threshold to return proposals with a classification score > box_score_thresh
'box_nms_thresh': 0.5, # NMS threshold for the prediction head
'box_detections_per_img': 100 # maximum number of detections per image, for all classes
}
قم بتنزيل الملف والاحتفاظ به ONNX_batch_model_generator_automl_for_images.py في الدليل الحالي لإرسال البرنامج النصي. استخدم مهمة الأمر التالي لإرسال البرنامج النصي ONNX_batch_model_generator_automl_for_images.py المتاح في مستودع azureml-examples GitHub، لإنشاء نموذج ONNX بحجم دفعة معينة. في التعليمات البرمجية التالية، يتم استخدام بيئة النموذج المُدرب لإرسال هذا البرنامج النصي لإنشاء نموذج ONNX وحفظه في دليل المخرجات.
لتصنيف الصور متعدد الفئات، يدعم نموذج ONNX الذي تم إنشاؤه أفضل تشغيل فرعي لتسجيل الدفعات بشكل افتراضي. لذلك، لا توجد وسيطات خاصة بالنموذج مطلوبة لنوع المهمة ويمكنك التخطي إلى قسم تحميل التسميات وملفات نموذج ONNX.
لتصنيف الصور متعدد المسميات، يدعم نموذج ONNX الذي تم إنشاؤه أفضل تشغيل فرعي لتسجيل الدفعات بشكل افتراضي. لذلك، لا توجد وسيطات خاصة بالنموذج مطلوبة لنوع المهمة ويمكنك التخطي إلى قسم تحميل التسميات وملفات نموذج ONNX.
from azure.ai.ml import command
job = command(
code="./onnx_generator_files", # local path where the code is stored
command="python ONNX_batch_model_generator_automl_for_images.py --model_name ${{inputs.model_name}} --batch_size ${{inputs.batch_size}} --height_onnx ${{inputs.height_onnx}} --width_onnx ${{inputs.width_onnx}} --job_name ${{inputs.job_name}} --task_type ${{inputs.task_type}} --min_size ${{inputs.min_size}} --max_size ${{inputs.max_size}} --box_score_thresh ${{inputs.box_score_thresh}} --box_nms_thresh ${{inputs.box_nms_thresh}} --box_detections_per_img ${{inputs.box_detections_per_img}}",
inputs=inputs,
environment=env,
compute=compute_name,
display_name="ONNX-batch-model-generation-rcnn",
description="Use the PyTorch to generate ONNX batch scoring model.",
)
returned_job = ml_client.create_or_update(job)
ml_client.jobs.stream(returned_job.name)
from azure.ai.ml import command
job = command(
code="./onnx_generator_files", # local path where the code is stored
command="python ONNX_batch_model_generator_automl_for_images.py --model_name ${{inputs.model_name}} --batch_size ${{inputs.batch_size}} --height_onnx ${{inputs.height_onnx}} --width_onnx ${{inputs.width_onnx}} --job_name ${{inputs.job_name}} --task_type ${{inputs.task_type}} --img_size ${{inputs.img_size}} --model_size ${{inputs.model_size}} --box_score_thresh ${{inputs.box_score_thresh}} --box_iou_thresh ${{inputs.box_iou_thresh}}",
inputs=inputs,
environment=env,
compute=compute_name,
display_name="ONNX-batch-model-generation",
description="Use the PyTorch to generate ONNX batch scoring model.",
)
returned_job = ml_client.create_or_update(job)
ml_client.jobs.stream(returned_job.name)
from azure.ai.ml import command
job = command(
code="./onnx_generator_files", # local path where the code is stored
command="python ONNX_batch_model_generator_automl_for_images.py --model_name ${{inputs.model_name}} --batch_size ${{inputs.batch_size}} --height_onnx ${{inputs.height_onnx}} --width_onnx ${{inputs.width_onnx}} --job_name ${{inputs.job_name}} --task_type ${{inputs.task_type}} --min_size ${{inputs.min_size}} --max_size ${{inputs.max_size}} --box_score_thresh ${{inputs.box_score_thresh}} --box_nms_thresh ${{inputs.box_nms_thresh}} --box_detections_per_img ${{inputs.box_detections_per_img}}",
inputs=inputs,
environment=env,
compute=compute_name,
display_name="ONNX-batch-model-generation-maskrcnn",
description="Use the PyTorch to generate ONNX batch scoring model.",
)
returned_job = ml_client.create_or_update(job)
ml_client.jobs.stream(returned_job.name)
بمجرد إنشاء نموذج الدفعة، قم بتنزيله إما من المخرجات + التسجيلات>المخرجات يدويًا من خلال واجهة المستخدم، أو استخدم الأسلوب التالي:
batch_size = 8 # use the batch size used to generate the model
returned_job_run = mlflow_client.get_run(returned_job.name)
# Download run's artifacts/outputs
onnx_model_path = mlflow_client.download_artifacts(
returned_job_run.info.run_id, 'outputs/model_'+str(batch_size)+'.onnx', local_dir
)
بعد تنزيل النموذج، يمكنك استخدام حزمة ONNX Runtime Python لإجراء الاستنتاج باستخدام ملف model.onnx. لأغراض التوضيح، تستخدم هذه المقالة مجموعات البيانات من كيفية إعداد مجموعات بيانات الصور في كل مهمة للرؤية.
قمنا بتدريب النماذج لجميع مهام الرؤية مع مجموعات البيانات الخاصة بها لإظهار استنتاج نموذج ONNX.
تحميل التسميات وملفات نموذج ONNX
تقوم القصاصة البرمجية التالية بتحميل labels.json، حيث أسماء الفئات المرتبة. أي أنه، إذا كان نموذج ONNX يتنبأ بمعرّف التسمية أنه 2، فإنه يتوافق مع اسم التسمية المُحدّد في الفهرس الثالث في ملف labels.json.
import json
import onnxruntime
labels_file = "automl_models/labels.json"
with open(labels_file) as f:
classes = json.load(f)
print(classes)
try:
session = onnxruntime.InferenceSession(onnx_model_path)
print("ONNX model loaded...")
except Exception as e:
print("Error loading ONNX file: ", str(e))
الحصول على تفاصيل الإدخال والإخراج المتوقعة لنموذج ONNX
عندما توافر النموذج، من المهم معرفة بعض التفاصيل الخاصة بالنموذج والمهام. تتضمن هذه التفاصيل عدد المُدخلات وعدد المُخرجات، وشكل الإدخال المتوقع أو تنسيق المعالجة المسبقة للصورة، وشكل الإخراج لتعرف المخرجات الخاصة بالنموذج أو بالمهمة.
sess_input = session.get_inputs()
sess_output = session.get_outputs()
print(f"No. of inputs : {len(sess_input)}, No. of outputs : {len(sess_output)}")
for idx, input_ in enumerate(range(len(sess_input))):
input_name = sess_input[input_].name
input_shape = sess_input[input_].shape
input_type = sess_input[input_].type
print(f"{idx} Input name : { input_name }, Input shape : {input_shape}, \
Input type : {input_type}")
for idx, output in enumerate(range(len(sess_output))):
output_name = sess_output[output].name
output_shape = sess_output[output].shape
output_type = sess_output[output].type
print(f" {idx} Output name : {output_name}, Output shape : {output_shape}, \
Output type : {output_type}")
تنسيقات الإدخال والإخراج المتوقعة لنموذج ONNX
يحتوي كل نموذج من نماذج ONNX على مجموعة مُحددة مسبقًا من تنسيقات الإدخال والإخراج.
يُطبّق ذلك المثال النموذج المُدرَّب على مجموعة بيانات fridgeObjects مع وجود 134 صورة و4 فئات / تسميات لتوضيح استنتاج نموذج ONNX. لمزيد من المعلومات حول تدريب مهمة تصنيف الصور، راجع دفتر ملاحظات تصنيف للصور متعدد الفئات.
تنسيق الإدخال
إن الإدخال هو صورة معالجة مسبقًا.
اسم الإدخال
شكل الإدخال
نوع الإدخال
الوصف
input1
(batch_size, num_channels, height, width)
ndarray(حر)
إن الإدخال هو صورة معالجة مسبقًا، بها شكل (1, 3, 224, 224) بحجم دفعة قدره 1، وارتفاع وعرض يبلغ 224. تتوافق هذه الأرقام مع القيم المستخدمة في crop_size بمثالٍ للتدريب.
نموذج الإخراج
إن الإخراج عبارة عن صفيف logit لجميع الفئات/التسميات.
اسم الإخراج
شكل الإخراج
نوع الإخراج
الوصف
output1
(batch_size, num_classes)
ndarray(حر)
يرجع النموذج logits (بدون softmax). على سبيل المثال، بالنسبة لحجم الدفعة 1 و4 فئات، فإنه يُرجع (1, 4).
إن الإدخال هو صورة معالجة مسبقًا، بها شكل (1, 3, 224, 224) بحجم دفعة قدره 1، وارتفاع وعرض يبلغ 224. تتوافق هذه الأرقام مع القيم المستخدمة في crop_size بمثالٍ للتدريب.
نموذج الإخراج
إن الإخراج عبارة عن صفيف logit لجميع الفئات/التسميات.
اسم الإخراج
شكل الإخراج
نوع الإخراج
الوصف
output1
(batch_size, num_classes)
ndarray(حر)
يرجع النموذج logits (بدون sigmoid). على سبيل المثال، بالنسبة لحجم الدفعة 1 و4 فئات، فإنه يُرجع (1, 4).
يستخدم مثال الكشف عن العناصر النموذج المُدرَّب على مجموعة بيانات الكشف عن fridgeObjects من 128 صورة و4 فئات/تسميات لتوضيح استنتاج نموذج ONNX. يدرب هذا المثال نماذج Faster R-CNN لتوضيح خطوات الاستنتاج. لمزيد من المعلومات حول تدريب نماذج الكشف عن العناصر، راجع دفتر ملاحظات الكشف عن العناصر.
تنسيق الإدخال
إن الإدخال هو صورة معالجة مسبقًا.
اسم الإدخال
شكل الإدخال
نوع الإدخال
الوصف
إدخال
(batch_size, num_channels, height, width)
ndarray(حر)
إن الإدخال هو صورة معالجة مسبقًا، بها شكل (1, 3, 600, 800) بحجم دفعة قدره 1، وارتفاع يبلغ 600 وعرض يبلغ 800.
نموذج الإخراج
إن الإخراج هو مجموعة من output_names والتنبؤات. وهنا، إن output_names و predictions هي قوائم طولها 3*batch_size لكل منها. إن ترتيب المخرجات في Faster R-CNN هو مربعات، وتسميات، ودرجات، في حين أن ترتيب مخرجات RetinaNet هي مربعات، ودرجات، وتسميات.
اسم الإخراج
شكل الإخراج
نوع الإخراج
الوصف
output_names
(3*batch_size)
قائمة المفاتيح
بالنسبة لحجم الدفعة 2، output_names هو ['boxes_0', 'labels_0', 'scores_0', 'boxes_1', 'labels_1', 'scores_1']
predictions
(3*batch_size)
قائمة ndarray(حر)
بالنسبة لحجم الدفعة 2، predictions يأخذ شكل [(n1_boxes, 4), (n1_boxes), (n1_boxes), (n2_boxes, 4), (n2_boxes), (n2_boxes)]. هنا، تتوافق قيم كل فهرس مع الفهرس نفسه في output_names.
يصف الجدول التالي المربعات والتسميات والنتائج التي يتم إرجاعها لكل عينة في دفعة من الصور.
الاسم
الشكل
النوع
الوصف
صناديق
(n_boxes, 4)، حيث يحتوي كل مربع على x_min, y_min, x_max, y_max
ndarray(حر)
يرجع النموذج n مربعات بإحداثيات أعلى اليمين وأسفل اليسار.
بطاقات عنونة
(n_boxes)
ndarray(حر)
مُعرف التسمية أو الفئة للعنصر في كل مربع.
الدرَجات
(n_boxes)
ndarray(حر)
درجة الثقة للعنصر في كل مربع.
يستخدم مثال الكشف عن العناصر النموذج المُدرَّب على مجموعة بيانات الكشف عن fridgeObjects من 128 صورة و4 فئات/تسميات لتوضيح استنتاج نموذج ONNX. يُدرّب هذا المثال نماذج YOLO لتوضيح خطوات الاستنتاج. لمزيد من المعلومات حول تدريب نماذج الكشف عن العناصر، راجع دفتر ملاحظات الكشف عن العناصر.
تنسيق الإدخال
إن الإدخال هو صورة معالجة مسبقًا، لديها شكل (1, 3, 640, 640) بحجم دفعة قدره 1، وارتفاع وعرض يبلغ 640. تتوافق هذه الأرقام مع القيم المستخدمة في مثال التدريب.
اسم الإدخال
شكل الإدخال
نوع الإدخال
الوصف
إدخال
(batch_size, num_channels, height, width)
ndarray(حر)
إن الإدخال هو صورة معالجة مسبقًا، لديها شكل (1, 3, 640, 640) بحجم دفعة قدره 1، وارتفاع يبلغ 640 وعرض يبلغ 640.
نموذج الإخراج
تحتوي تنبؤات نموذج ONNX على مخرجات متعددة. الإخراج الأول مطلوب لإجراء منع غير أقصى للكشف. لسهولة الاستخدام، يعرض «التعلم الآلي» التلقائي تنسيق الإخراج بعد خطوة المعالجة اللاحقة لـ NMS. إن الإخراج الناتج بعد NMS هو قائمة بالمربعات، والتسميات، والنقاط عن كل عينة في الدفعة.
اسم الإخراج
شكل الإخراج
نوع الإخراج
الوصف
المخرجات
(batch_size)
قائمة ndarray(حر)
يُرجع النموذج بإرجاع عمليات كشف المربع عن كل عينة في الدفعة
تشير كل خلية في القائمة إلى اكتشافات المربع عن عينة لديها شكل (n_boxes, 6)، حيث يحتوي كل مربع على x_min, y_min, x_max, y_max, confidence_score, class_id.
بالنسبة إلى مثال تجزئة المثيل، يمكنك استخدام نموذج Mask R-CNN المُدرّب على مجموعة بيانات fridgeObjects بها 128 صورة و4 فئات/تسميات لتوضيح استنتاج نموذج ONNX. لمزيد من المعلومات حول تدريب نموذج تجزئة المثيل، راجع دفتر ملاحظات تجزئة المثيل.
هام
يُدعم نموذج Mask R-CNN فقط للقيام بمهام تجزئة المثيل. تستند تنسيقات الإدخال والإخراج إلى نموذج Mask R-CNN فقط.
تنسيق الإدخال
إن الإدخال هو صورة معالجة مسبقًا. تم تصدير نموذج ONNX في Mask R-CNN للتصرف في صور مختلفة الأشكال. نوصي بتغيير حجمها إلى حجم ثابت يتوافق مع أحجام الصور المتدرب عليها، للحصول على أداء أفضل.
اسم الإدخال
شكل الإدخال
نوع الإدخال
الوصف
إدخال
(batch_size, num_channels, height, width)
ndarray(حر)
إن الإدخال هو صورة معالجة مسبقًا، لديها شكل (1, 3, input_image_height, input_image_width) بحجم دفعة قدره 1، وارتفاع وعرض مماثل لصورة الإدخال.
نموذج الإخراج
إن الإخراج هو مجموعة من output_names والتنبؤات. وهنا، إن output_names و predictions هي قوائم طولها 4*batch_size لكل منها.
اسم الإخراج
شكل الإخراج
نوع الإخراج
الوصف
output_names
(4*batch_size)
قائمة المفاتيح
بالنسبة لحجم الدفعة 2، output_names هو ['boxes_0', 'labels_0', 'scores_0', 'masks_0', 'boxes_1', 'labels_1', 'scores_1', 'masks_1']
predictions
(4*batch_size)
قائمة ndarray(حر)
بالنسبة لحجم الدفعة 2، predictions يأخذ شكل [(n1_boxes, 4), (n1_boxes), (n1_boxes), (n1_boxes, 1, height_onnx, width_onnx), (n2_boxes, 4), (n2_boxes), (n2_boxes), (n2_boxes, 1, height_onnx, width_onnx)]. هنا، تتوافق قيم كل فهرس مع الفهرس نفسه في output_names.
الاسم
الشكل
النوع
الوصف
صناديق
(n_boxes, 4)، حيث يحتوي كل مربع على x_min, y_min, x_max, y_max
ndarray(حر)
يرجع النموذج n مربعات بإحداثيات أعلى اليمين وأسفل اليسار.
بطاقات عنونة
(n_boxes)
ndarray(حر)
مُعرف التسمية أو الفئة للعنصر في كل مربع.
الدرَجات
(n_boxes)
ndarray(حر)
درجة الثقة للعنصر في كل مربع.
الأقنعة
(n_boxes, 1, height_onnx, width_onnx)
ndarray(حر)
أقنعة (مضلعات) الأغراض المكتشفة وارتفاع الشكل وعرض صورة الإدخال.
قد بإجراء خطوات ما قبل المعالجة التالية لاستنتاج نموذج ONNX:
قم بتحويل الصورة إلى RGB.
قم بتغيير حجم الصورة إلى قيم valid_resize_size و valid_resize_size التي تتوافق مع القيم المستخدمة في تحويل مجموعة بيانات التحقق من الصحة أثناء التدريب. إن القيمة الافتراضية لـ valid_resize_size هي 256.
قم باقتصاص الصورة من المركز إلى height_onnx_crop_size و width_onnx_crop_size. تتوافق مع valid_crop_size بقيمة افتراضية قدرها 224.
قم بتغيير HxWxC إلى CxHxW
قم بالتحويل إلى نوع حر.
قم بالضبط باستخدام mean = [0.485, 0.456, 0.406] في ImageNet و std = [0.229, 0.224, 0.225].
إذا اخترت قيم مختلفة للمقاييس الفائقةvalid_resize_size و valid_crop_sizeأثناء التدريب، يجب إذن استخدام هذه القيم.
import glob
import numpy as np
from PIL import Image
def preprocess(image, resize_size, crop_size_onnx):
"""Perform pre-processing on raw input image
:param image: raw input image
:type image: PIL image
:param resize_size: value to resize the image
:type image: Int
:param crop_size_onnx: expected height of an input image in onnx model
:type crop_size_onnx: Int
:return: pre-processed image in numpy format
:rtype: ndarray 1xCxHxW
"""
image = image.convert('RGB')
# resize
image = image.resize((resize_size, resize_size))
# center crop
left = (resize_size - crop_size_onnx)/2
top = (resize_size - crop_size_onnx)/2
right = (resize_size + crop_size_onnx)/2
bottom = (resize_size + crop_size_onnx)/2
image = image.crop((left, top, right, bottom))
np_image = np.array(image)
# HWC -> CHW
np_image = np_image.transpose(2, 0, 1) # CxHxW
# normalize the image
mean_vec = np.array([0.485, 0.456, 0.406])
std_vec = np.array([0.229, 0.224, 0.225])
norm_img_data = np.zeros(np_image.shape).astype('float32')
for i in range(np_image.shape[0]):
norm_img_data[i,:,:] = (np_image[i,:,:]/255 - mean_vec[i])/std_vec[i]
np_image = np.expand_dims(norm_img_data, axis=0) # 1xCxHxW
return np_image
# following code loads only batch_size number of images for demonstrating ONNX inference
# make sure that the data directory has at least batch_size number of images
test_images_path = "automl_models_multi_cls/test_images_dir/*" # replace with path to images
# Select batch size needed
batch_size = 8
# you can modify resize_size based on your trained model
resize_size = 256
# height and width will be the same for classification
crop_size_onnx = height_onnx_crop_size
image_files = glob.glob(test_images_path)
img_processed_list = []
for i in range(batch_size):
img = Image.open(image_files[i])
img_processed_list.append(preprocess(img, resize_size, crop_size_onnx))
if len(img_processed_list) > 1:
img_data = np.concatenate(img_processed_list)
elif len(img_processed_list) == 1:
img_data = img_processed_list[0]
else:
img_data = None
assert batch_size == img_data.shape[0]
يتضمن PyTorch
import glob
import torch
import numpy as np
from PIL import Image
from torchvision import transforms
def _make_3d_tensor(x) -> torch.Tensor:
"""This function is for images that have less channels.
:param x: input tensor
:type x: torch.Tensor
:return: return a tensor with the correct number of channels
:rtype: torch.Tensor
"""
return x if x.shape[0] == 3 else x.expand((3, x.shape[1], x.shape[2]))
def preprocess(image, resize_size, crop_size_onnx):
transform = transforms.Compose([
transforms.Resize(resize_size),
transforms.CenterCrop(crop_size_onnx),
transforms.ToTensor(),
transforms.Lambda(_make_3d_tensor),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
img_data = transform(image)
img_data = img_data.numpy()
img_data = np.expand_dims(img_data, axis=0)
return img_data
# following code loads only batch_size number of images for demonstrating ONNX inference
# make sure that the data directory has at least batch_size number of images
test_images_path = "automl_models_multi_cls/test_images_dir/*" # replace with path to images
# Select batch size needed
batch_size = 8
# you can modify resize_size based on your trained model
resize_size = 256
# height and width will be the same for classification
crop_size_onnx = height_onnx_crop_size
image_files = glob.glob(test_images_path)
img_processed_list = []
for i in range(batch_size):
img = Image.open(image_files[i])
img_processed_list.append(preprocess(img, resize_size, crop_size_onnx))
if len(img_processed_list) > 1:
img_data = np.concatenate(img_processed_list)
elif len(img_processed_list) == 1:
img_data = img_processed_list[0]
else:
img_data = None
assert batch_size == img_data.shape[0]
قد بإجراء خطوات ما قبل المعالجة التالية لاستنتاج نموذج ONNX. إن هذه الخطوات هي الخطوات نفسها لتصنيف الصور متعدد الفئات.
قم بتحويل الصورة إلى RGB.
قم بتغيير حجم الصورة إلى قيم valid_resize_size و valid_resize_size التي تتوافق مع القيم المستخدمة في تحويل مجموعة بيانات التحقق من الصحة أثناء التدريب. إن القيمة الافتراضية لـ valid_resize_size هي 256.
قم باقتصاص الصورة من المركز إلى height_onnx_crop_size و width_onnx_crop_size. تتوافق مع valid_crop_size بقيمة افتراضية قدرها 224.
قم بتغيير HxWxC إلى CxHxW
قم بالتحويل إلى نوع حر.
قم بالضبط باستخدام mean = [0.485, 0.456, 0.406] في ImageNet و std = [0.229, 0.224, 0.225].
إذا اخترت قيم مختلفة للمقاييس الفائقةvalid_resize_size و valid_crop_sizeأثناء التدريب، يجب إذن استخدام هذه القيم.
import glob
import numpy as np
from PIL import Image
def preprocess(image, resize_size, crop_size_onnx):
"""Perform pre-processing on raw input image
:param image: raw input image
:type image: PIL image
:param resize_size: value to resize the image
:type image: Int
:param crop_size_onnx: expected height of an input image in onnx model
:type crop_size_onnx: Int
:return: pre-processed image in numpy format
:rtype: ndarray 1xCxHxW
"""
image = image.convert('RGB')
# resize
image = image.resize((resize_size, resize_size))
# center crop
left = (resize_size - crop_size_onnx)/2
top = (resize_size - crop_size_onnx)/2
right = (resize_size + crop_size_onnx)/2
bottom = (resize_size + crop_size_onnx)/2
image = image.crop((left, top, right, bottom))
np_image = np.array(image)
# HWC -> CHW
np_image = np_image.transpose(2, 0, 1) # CxHxW
# normalize the image
mean_vec = np.array([0.485, 0.456, 0.406])
std_vec = np.array([0.229, 0.224, 0.225])
norm_img_data = np.zeros(np_image.shape).astype('float32')
for i in range(np_image.shape[0]):
norm_img_data[i,:,:] = (np_image[i,:,:] / 255 - mean_vec[i]) / std_vec[i]
np_image = np.expand_dims(norm_img_data, axis=0) # 1xCxHxW
return np_image
# following code loads only batch_size number of images for demonstrating ONNX inference
# make sure that the data directory has at least batch_size number of images
test_images_path = "automl_models_multi_label/test_images_dir/*" # replace with path to images
# Select batch size needed
batch_size = 8
# you can modify resize_size based on your trained model
resize_size = 256
# height and width will be the same for classification
crop_size_onnx = height_onnx_crop_size
image_files = glob.glob(test_images_path)
img_processed_list = []
for i in range(batch_size):
img = Image.open(image_files[i])
img_processed_list.append(preprocess(img, resize_size, crop_size_onnx))
if len(img_processed_list) > 1:
img_data = np.concatenate(img_processed_list)
elif len(img_processed_list) == 1:
img_data = img_processed_list[0]
else:
img_data = None
assert batch_size == img_data.shape[0]
يتضمن PyTorch
import glob
import torch
import numpy as np
from PIL import Image
from torchvision import transforms
def _make_3d_tensor(x) -> torch.Tensor:
"""This function is for images that have less channels.
:param x: input tensor
:type x: torch.Tensor
:return: return a tensor with the correct number of channels
:rtype: torch.Tensor
"""
return x if x.shape[0] == 3 else x.expand((3, x.shape[1], x.shape[2]))
def preprocess(image, resize_size, crop_size_onnx):
"""Perform pre-processing on raw input image
:param image: raw input image
:type image: PIL image
:param resize_size: value to resize the image
:type image: Int
:param crop_size_onnx: expected height of an input image in onnx model
:type crop_size_onnx: Int
:return: pre-processed image in numpy format
:rtype: ndarray 1xCxHxW
"""
transform = transforms.Compose([
transforms.Resize(resize_size),
transforms.CenterCrop(crop_size_onnx),
transforms.ToTensor(),
transforms.Lambda(_make_3d_tensor),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
img_data = transform(image)
img_data = img_data.numpy()
img_data = np.expand_dims(img_data, axis=0)
return img_data
# following code loads only batch_size number of images for demonstrating ONNX inference
# make sure that the data directory has at least batch_size number of images
test_images_path = "automl_models_multi_label/test_images_dir/*" # replace with path to images
# Select batch size needed
batch_size = 8
# you can modify resize_size based on your trained model
resize_size = 256
# height and width will be the same for classification
crop_size_onnx = height_onnx_crop_size
image_files = glob.glob(test_images_path)
img_processed_list = []
for i in range(batch_size):
img = Image.open(image_files[i])
img_processed_list.append(preprocess(img, resize_size, crop_size_onnx))
if len(img_processed_list) > 1:
img_data = np.concatenate(img_processed_list)
elif len(img_processed_list) == 1:
img_data = img_processed_list[0]
else:
img_data = None
assert batch_size == img_data.shape[0]
للكشف عن الكائنات باستخدام بنية R-CNN الأسرع، اتبع نفس خطوات المعالجة المسبقة لتصنيف الصور، باستثناء اقتصاص الصور. يمكنك تغيير حجم الصورة بارتفاع 600 والعرض 800. يمكنك الحصول على الارتفاع والعرض المتوقع للإدخال باستخدام التعليمات البرمجية التالية.
import glob
import numpy as np
from PIL import Image
def preprocess(image, height_onnx, width_onnx):
"""Perform pre-processing on raw input image
:param image: raw input image
:type image: PIL image
:param height_onnx: expected height of an input image in onnx model
:type height_onnx: Int
:param width_onnx: expected width of an input image in onnx model
:type width_onnx: Int
:return: pre-processed image in numpy format
:rtype: ndarray 1xCxHxW
"""
image = image.convert('RGB')
image = image.resize((width_onnx, height_onnx))
np_image = np.array(image)
# HWC -> CHW
np_image = np_image.transpose(2, 0, 1) # CxHxW
# normalize the image
mean_vec = np.array([0.485, 0.456, 0.406])
std_vec = np.array([0.229, 0.224, 0.225])
norm_img_data = np.zeros(np_image.shape).astype('float32')
for i in range(np_image.shape[0]):
norm_img_data[i,:,:] = (np_image[i,:,:] / 255 - mean_vec[i]) / std_vec[i]
np_image = np.expand_dims(norm_img_data, axis=0) # 1xCxHxW
return np_image
# following code loads only batch_size number of images for demonstrating ONNX inference
# make sure that the data directory has at least batch_size number of images
test_images_path = "automl_models_od/test_images_dir/*" # replace with path to images
image_files = glob.glob(test_images_path)
img_processed_list = []
for i in range(batch_size):
img = Image.open(image_files[i])
img_processed_list.append(preprocess(img, height_onnx, width_onnx))
if len(img_processed_list) > 1:
img_data = np.concatenate(img_processed_list)
elif len(img_processed_list) == 1:
img_data = img_processed_list[0]
else:
img_data = None
assert batch_size == img_data.shape[0]
للكشف عن الكائنات باستخدام بنية YOLO، اتبع نفس خطوات المعالجة المسبقة مثل تصنيف الصور، باستثناء اقتصاص الصور. يمكنك تغيير حجم الصورة بارتفاع 600 وعرض 800، والحصول على الارتفاع والعرض المتوقعين للإدخال باستخدام التعليمات البرمجية التالية.
import glob
import numpy as np
from yolo_onnx_preprocessing_utils import preprocess
# use height and width based on the generated model
test_images_path = "automl_models_od_yolo/test_images_dir/*" # replace with path to images
image_files = glob.glob(test_images_path)
img_processed_list = []
pad_list = []
for i in range(batch_size):
img_processed, pad = preprocess(image_files[i])
img_processed_list.append(img_processed)
pad_list.append(pad)
if len(img_processed_list) > 1:
img_data = np.concatenate(img_processed_list)
elif len(img_processed_list) == 1:
img_data = img_processed_list[0]
else:
img_data = None
assert batch_size == img_data.shape[0]
هام
يُدعم نموذج Mask R-CNN فقط للقيام بمهام تجزئة المثيل. تستند خطوات ما قبل المعالجة إلى Mask R-CNN فقط.
قد بإجراء خطوات ما قبل المعالجة التالية لاستنتاج نموذج ONNX:
قم بتحويل الصورة إلى RGB.
قم بتغيير حجم الصورة.
قم بتغيير HxWxC إلى CxHxW
قم بالتحويل إلى نوع حر.
قم بالضبط باستخدام mean = [0.485, 0.456, 0.406] في ImageNet و std = [0.229, 0.224, 0.225].
بالنسبة إلى resize_height و resize_width، يمكنك أيضًا استخدام القيم المستخدمة أثناء التدريب، المُضمنة في min_size و max_sizeالتعليمات الفائقة في Mask R-CNN.
import glob
import numpy as np
from PIL import Image
def preprocess(image, resize_height, resize_width):
"""Perform pre-processing on raw input image
:param image: raw input image
:type image: PIL image
:param resize_height: resize height of an input image
:type resize_height: Int
:param resize_width: resize width of an input image
:type resize_width: Int
:return: pre-processed image in numpy format
:rtype: ndarray of shape 1xCxHxW
"""
image = image.convert('RGB')
image = image.resize((resize_width, resize_height))
np_image = np.array(image)
# HWC -> CHW
np_image = np_image.transpose(2, 0, 1) # CxHxW
# normalize the image
mean_vec = np.array([0.485, 0.456, 0.406])
std_vec = np.array([0.229, 0.224, 0.225])
norm_img_data = np.zeros(np_image.shape).astype('float32')
for i in range(np_image.shape[0]):
norm_img_data[i,:,:] = (np_image[i,:,:]/255 - mean_vec[i])/std_vec[i]
np_image = np.expand_dims(norm_img_data, axis=0) # 1xCxHxW
return np_image
# following code loads only batch_size number of images for demonstrating ONNX inference
# make sure that the data directory has at least batch_size number of images
# use height and width based on the trained model
# use height and width based on the generated model
test_images_path = "automl_models_is/test_images_dir/*" # replace with path to images
image_files = glob.glob(test_images_path)
img_processed_list = []
for i in range(batch_size):
img = Image.open(image_files[i])
img_processed_list.append(preprocess(img, height_onnx, width_onnx))
if len(img_processed_list) > 1:
img_data = np.concatenate(img_processed_list)
elif len(img_processed_list) == 1:
img_data = img_processed_list[0]
else:
img_data = None
assert batch_size == img_data.shape[0]
الاستنتاج باستخدام ONNX Runtime
يختلف الاستنتاج باستخدام ONNX Runtime في كل مهمة من مهام رؤية الكمبيوتر.
def get_predictions_from_ONNX(onnx_session, img_data):
"""Perform predictions with ONNX runtime
:param onnx_session: onnx model session
:type onnx_session: class InferenceSession
:param img_data: pre-processed numpy image
:type img_data: ndarray with shape 1xCxHxW
:return: scores with shapes
(1, No. of classes in training dataset)
:rtype: numpy array
"""
sess_input = onnx_session.get_inputs()
sess_output = onnx_session.get_outputs()
print(f"No. of inputs : {len(sess_input)}, No. of outputs : {len(sess_output)}")
# predict with ONNX Runtime
output_names = [ output.name for output in sess_output]
scores = onnx_session.run(output_names=output_names,\
input_feed={sess_input[0].name: img_data})
return scores[0]
scores = get_predictions_from_ONNX(session, img_data)
def get_predictions_from_ONNX(onnx_session,img_data):
"""Perform predictions with ONNX runtime
:param onnx_session: onnx model session
:type onnx_session: class InferenceSession
:param img_data: pre-processed numpy image
:type img_data: ndarray with shape 1xCxHxW
:return: scores with shapes
(1, No. of classes in training dataset)
:rtype: numpy array
"""
sess_input = onnx_session.get_inputs()
sess_output = onnx_session.get_outputs()
print(f"No. of inputs : {len(sess_input)}, No. of outputs : {len(sess_output)}")
# predict with ONNX Runtime
output_names = [ output.name for output in sess_output]
scores = onnx_session.run(output_names=output_names,\
input_feed={sess_input[0].name: img_data})
return scores[0]
scores = get_predictions_from_ONNX(session, img_data)
def get_predictions_from_ONNX(onnx_session, img_data):
"""perform predictions with ONNX runtime
:param onnx_session: onnx model session
:type onnx_session: class InferenceSession
:param img_data: pre-processed numpy image
:type img_data: ndarray with shape 1xCxHxW
:return: boxes, labels , scores
(No. of boxes, 4) (No. of boxes,) (No. of boxes,)
:rtype: tuple
"""
sess_input = onnx_session.get_inputs()
sess_output = onnx_session.get_outputs()
# predict with ONNX Runtime
output_names = [output.name for output in sess_output]
predictions = onnx_session.run(output_names=output_names,\
input_feed={sess_input[0].name: img_data})
return output_names, predictions
output_names, predictions = get_predictions_from_ONNX(session, img_data)
def get_predictions_from_ONNX(onnx_session,img_data):
"""perform predictions with ONNX Runtime
:param onnx_session: onnx model session
:type onnx_session: class InferenceSession
:param img_data: pre-processed numpy image
:type img_data: ndarray with shape 1xCxHxW
:return: boxes, labels , scores
:rtype: list
"""
sess_input = onnx_session.get_inputs()
sess_output = onnx_session.get_outputs()
# predict with ONNX Runtime
output_names = [ output.name for output in sess_output]
pred = onnx_session.run(output_names=output_names,\
input_feed={sess_input[0].name: img_data})
return pred[0]
result = get_predictions_from_ONNX(session, img_data)
يتوقع نموذج تجزئة المثيل المربعات، والتسميات، والدرجات، والأقنعة. يُخرج ONNX قناع متوقع لكل مثيل، إلى جانب مربعات الإحاطة المُقابلة ودرجة ثقة الفئة. قد تحتاج إلى التحويل من قناع ثنائي إلى مضلع إذا لزم الأمر.
def get_predictions_from_ONNX(onnx_session, img_data):
"""Perform predictions with ONNX runtime
:param onnx_session: onnx model session
:type onnx_session: class InferenceSession
:param img_data: pre-processed numpy image
:type img_data: ndarray with shape 1xCxHxW
:return: boxes, labels , scores , masks with shapes
(No. of instances, 4) (No. of instances,) (No. of instances,)
(No. of instances, 1, HEIGHT, WIDTH))
:rtype: tuple
"""
sess_input = onnx_session.get_inputs()
sess_output = onnx_session.get_outputs()
# predict with ONNX Runtime
output_names = [ output.name for output in sess_output]
predictions = onnx_session.run(output_names=output_names,\
input_feed={sess_input[0].name: img_data})
return output_names, predictions
output_names, predictions = get_predictions_from_ONNX(session, img_data)
conf_scores = torch.nn.functional.softmax(torch.from_numpy(scores), dim=1)
class_preds = torch.argmax(conf_scores, dim=1)
print("predicted classes:", ([(class_idx.item(), classes[class_idx]) for class_idx in class_preds]))
تختلف هذه الخطوة عن التصنيف متعدد الفئات. تحتاج إلى تطبيق sigmoid على logits (إخراج ONNX) للحصول على درجات الثقة لتصنيف الصور متعدد التسميات.
بدون PyTorch
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# we apply a threshold of 0.5 on confidence scores
score_threshold = 0.5
conf_scores = sigmoid(scores)
image_wise_preds = np.where(conf_scores > score_threshold)
for image_idx, class_idx in zip(image_wise_preds[0], image_wise_preds[1]):
print('image: {}, class_index: {}, class_name: {}'.format(image_files[image_idx], class_idx, classes[class_idx]))
يتضمن PyTorch
# we apply a threshold of 0.5 on confidence scores
score_threshold = 0.5
conf_scores = torch.sigmoid(torch.from_numpy(scores))
image_wise_preds = torch.where(conf_scores > score_threshold)
for image_idx, class_idx in zip(image_wise_preds[0], image_wise_preds[1]):
print('image: {}, class_index: {}, class_name: {}'.format(image_files[image_idx], class_idx, classes[class_idx]))
بالنسبة للتصنيف متعدد الفئات والتسميات المتعددة، يمكنك اتباع نفس الخطوات المذكورة سابقا لجميع بنيات النموذج المدعومة في AutoML.
للكشف عن العناصر، تقع التنبؤات تلقائيًا في المقياس height_onnx، و width_onnx. لتحويل إحداثيات المربع المتوقع إلى الأبعاد الأصلية، يمكنك تنفيذ العمليات الحسابية التالية.
Xmin * original_width/width_onnx
Ymin * original_height/ height_onnx
Xmax * original_width/width_onnx
Ymax * original_height/height_onnx
ومن بين الخيارات الأخرى هو استخدام التعليمات البرمجية التالية لتغيير حجم أبعاد المربع ليقع في نطاق [0، 1]. يسمح القيام بذلك بضرب إحداثيات المربع في ارتفاع الصور الأصلية وعرضها في الإحداثيات المعنية (كما هو موضح في قسم تصور التنبؤات) للحصول على مربعات في أبعاد الصورة الأصلية.
def _get_box_dims(image_shape, box):
box_keys = ['topX', 'topY', 'bottomX', 'bottomY']
height, width = image_shape[0], image_shape[1]
box_dims = dict(zip(box_keys, [coordinate.item() for coordinate in box]))
box_dims['topX'] = box_dims['topX'] * 1.0 / width
box_dims['bottomX'] = box_dims['bottomX'] * 1.0 / width
box_dims['topY'] = box_dims['topY'] * 1.0 / height
box_dims['bottomY'] = box_dims['bottomY'] * 1.0 / height
return box_dims
def _get_prediction(boxes, labels, scores, image_shape, classes):
bounding_boxes = []
for box, label_index, score in zip(boxes, labels, scores):
box_dims = _get_box_dims(image_shape, box)
box_record = {'box': box_dims,
'label': classes[label_index],
'score': score.item()}
bounding_boxes.append(box_record)
return bounding_boxes
# Filter the results with threshold.
# Please replace the threshold for your test scenario.
score_threshold = 0.8
filtered_boxes_batch = []
for batch_sample in range(0, batch_size*3, 3):
# in case of retinanet change the order of boxes, labels, scores to boxes, scores, labels
# confirm the same from order of boxes, labels, scores output_names
boxes, labels, scores = predictions[batch_sample], predictions[batch_sample + 1], predictions[batch_sample + 2]
bounding_boxes = _get_prediction(boxes, labels, scores, (height_onnx, width_onnx), classes)
filtered_bounding_boxes = [box for box in bounding_boxes if box['score'] >= score_threshold]
filtered_boxes_batch.append(filtered_bounding_boxes)
تنشئ التعليمات البرمجية التالية المربعات، والتسميات، والدرجات. استخدم تفاصيل مربع الإحاطة لتنفيذ خطوات ما بعد المعالجة نفسها كما فعلت في نموذج Faster R-CNN.
يمكنك إما أن تستخدم الخطوات المذكورة في Faster R-CNN (في حالة Mask R-CNN، تحتوي كل عينة على أربعة مربعات للعناصر، أو تسميات، أو درجات، أو أقنعة) أو أن ترجع إلى قسم تصور التنبؤات لتجزئة المثيل.