docs: Update README and compilation guides for clarity and consistency, including path corrections and improved formatting. Add copyright notices to source files and adjust file permissions for several scripts and directories.
This commit is contained in:
parent
f960c5030d
commit
bd891a96dd
136 changed files with 14413 additions and 9399 deletions
|
|
@ -0,0 +1,104 @@
|
|||
# blazepose_detect
|
||||
|
||||
## 1.Overview
|
||||
|
||||
BlazePose Detection was introduced by Google as part of the MediaPipe framework, providing fast and lightweight person detection optimized for real-time performance on mobile and edge devices. The detector identifies the human region of interest (ROI) in an image, ensuring stable and efficient pose tracking in subsequent stages.
|
||||
|
||||
## 2.Model Download
|
||||
|
||||
- **Open Source model**
|
||||
|
||||
- **Open Source projects:** https://github.com/google-ai-edge/mediapipe/tree/master
|
||||
|
||||
- **Download weights**
|
||||
|
||||
wget https://storage.googleapis.com/mediapipe-assets/pose_detection.tflite
|
||||
|
||||
## 3. Model Conversion
|
||||
|
||||
```
|
||||
cd model
|
||||
Usage: ./adla_convert.sh model_path adla_toolkit_path target_platform
|
||||
|
||||
example
|
||||
./adla_convert.sh pose_detection.tflite /xxxx/adla-toolkit-binary-3.2.9.3 PRODUCT_PID0XA005
|
||||
./adla_convert.sh pose_detection.tflite /xxxx/adla-toolkit-binary-3.2.9.3 PRODUCT_PID0XA005
|
||||
./adla_convert.sh pose_detection.tflite /xxxx/adla-toolkit-binary-3.2.9.3 PRODUCT_PID0XA005
|
||||
```
|
||||
|
||||
| Parameter | Description |
|
||||
| ----------------- | ------------------------------------------------------------ |
|
||||
| model_path | onnx model path |
|
||||
| adla_toolkit_path | path to adla_toolkit |
|
||||
| target_platform | Specify target platform. for A311D2: PRODUCT_PID0XA003. for S905X5: PRODUCT_PID0XA005 |
|
||||
|
||||
|
||||
|
||||
## 4. Demo Run
|
||||
|
||||
### CPP
|
||||
|
||||
#### 1. Compile
|
||||
|
||||
**Prerequisites:**
|
||||
|
||||
- Android NDK (r25e recommended)
|
||||
- `ANDROID_NDK_PATH` environment variable set
|
||||
|
||||
**Build:**
|
||||
```bash
|
||||
# Build for arm64-v8a
|
||||
cd examples/blazepose_detect/cpp
|
||||
./build-android.sh -a arm64-v8a
|
||||
```
|
||||
|
||||
The executable will be generated at `build/android/blazepose_detect_demo` (Note: executable name may vary, verify in build folder).
|
||||
|
||||
#### 2. Run
|
||||
|
||||
```bash
|
||||
# Push executable to device
|
||||
adb push build/android/blazepose_detect_demo /data/local/tmp/
|
||||
adb push model/blazepose_detect_int8_A311D2.adla /data/local/tmp/
|
||||
adb push test_image.jpg /data/local/tmp/
|
||||
|
||||
# Run on device
|
||||
adb shell
|
||||
cd /data/local/tmp
|
||||
chmod +x blazepose_detect_demo
|
||||
export LD_LIBRARY_PATH=/vendor/lib64 or (/vendor/lib)
|
||||
|
||||
# Usage: ./blazepose_detect_demo <model_path> <image_path>
|
||||
./blazepose_detect_demo blazepose_detect_int8_A311D2.adla test_image.jpg"
|
||||
```
|
||||
|
||||
**Note:** Replace `blazepose_detect_int8_A311D2.adla` with your actual model file path.
|
||||
|
||||
### Python
|
||||
|
||||
**Prerequisites:**
|
||||
- Python 3.10
|
||||
- Required packages: `numpy`, `opencv-python`, `amlnnlite`
|
||||
|
||||
**Install dependencies:**
|
||||
```bash
|
||||
pip install numpy opencv-python amlnnlite-1.0.0-cp310-cp310-linux_aarch64.whl
|
||||
```
|
||||
|
||||
**Run on device:**
|
||||
```bash
|
||||
python blazepose_detect.py --model-path ./blazepose_detect_int8_A311D2.adla
|
||||
```
|
||||
|
||||
The script will automatically process all image files (`.jpg`, `.jpeg`, `.png`, `.bmp`) in the current directory and save results to a `{model_name}_result` folder.
|
||||
|
||||
## 5.Results
|
||||
The program will print the detection count and inference time. The result image with bounding boxes will be saved to the specified output path (`result.jpg` by default).
|
||||
|
||||
|
||||
You can pull the result image back to view it:
|
||||
```bash
|
||||
adb pull result.jpg.
|
||||
```
|
||||

|
||||
|
||||
0
examples/blazepose_detect/cpp/.gitkeep
Normal file → Executable file
0
examples/blazepose_detect/cpp/.gitkeep
Normal file → Executable file
77
examples/blazepose_detect/cpp/build-android.sh
Executable file
77
examples/blazepose_detect/cpp/build-android.sh
Executable file
|
|
@ -0,0 +1,77 @@
|
|||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
#
|
||||
# Copyright (C) 2024–2025 Amlogic, Inc. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
usage() {
|
||||
echo "Usage: $0 [-a <target_abi>]"
|
||||
echo " -a <target_abi> : Target ABI (default: arm64-v8a)"
|
||||
echo " -h : Show this help message"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Default values
|
||||
TARGET_ABI=arm64-v8a
|
||||
|
||||
# Parse arguments
|
||||
while getopts 'a:h' opt; do
|
||||
case "$opt" in
|
||||
a)
|
||||
TARGET_ABI=$OPTARG
|
||||
;;
|
||||
h)
|
||||
usage
|
||||
;;
|
||||
*)
|
||||
usage
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [ -z "${ANDROID_NDK_PATH}" ]; then
|
||||
if [ -n "${ANDROID_NDK}" ]; then
|
||||
ANDROID_NDK_PATH=${ANDROID_NDK}
|
||||
elif [ -n "${ANDROID_NDK_HOME}" ]; then
|
||||
ANDROID_NDK_PATH=${ANDROID_NDK_HOME}
|
||||
else
|
||||
echo "Error: ANDROID_NDK_PATH is not set."
|
||||
echo "Please set ANDROID_NDK_PATH to your Android NDK directory."
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
ROOT_PWD=$(cd "$(dirname $0)" && pwd)
|
||||
BUILD_DIR=${ROOT_PWD}/build/android
|
||||
|
||||
echo "Building for Android..."
|
||||
echo "NDK_PATH: ${ANDROID_NDK_PATH}"
|
||||
echo "TARGET_ABI: ${TARGET_ABI}"
|
||||
echo "BUILD_DIR: ${BUILD_DIR}"
|
||||
|
||||
mkdir -p ${BUILD_DIR}
|
||||
cd ${BUILD_DIR}
|
||||
|
||||
cmake ../../src \
|
||||
-DCMAKE_TOOLCHAIN_FILE=${ANDROID_NDK_PATH}/build/cmake/android.toolchain.cmake \
|
||||
-DANDROID_ABI=${TARGET_ABI} \
|
||||
-DANDROID_PLATFORM=android-24 \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DOpenCV_DIR=${ROOT_PWD}/../../../dependency/opencv/opencv-android-sdk-build/sdk/native/jni/abi-${TARGET_ABI}
|
||||
|
||||
make -j4
|
||||
|
||||
echo "Build complete. Executable in ${BUILD_DIR}/blazepose_detect_demo"
|
||||
168
examples/blazepose_detect/cpp/build-linux.sh
Executable file
168
examples/blazepose_detect/cpp/build-linux.sh
Executable file
|
|
@ -0,0 +1,168 @@
|
|||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
#
|
||||
# Copyright (C) 2024–2025 Amlogic, Inc. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
usage() {
|
||||
echo "Usage: $0 [-m <mode>] [-a <target_arch>] [-b <arch_bits>] [-s <yocto_sdk_root>] [-t <toolchain_file>]"
|
||||
echo " -m <mode> : Build mode: 'linux' or 'yocto' (default: linux)"
|
||||
echo " -a <target> : Target arch for linux mode (default: aarch64)"
|
||||
echo " -b <arch_bits> : Arch bits for yocto mode: 32 or 64 (default: 64)"
|
||||
echo " -s <sdk_root> : Yocto SDK root path (overrides YOCTO_SDK_ROOT env var)"
|
||||
echo " -t <toolchain> : CMake toolchain file (overrides TOOLCHAIN_FILE env var)"
|
||||
echo " -h : Show this help message"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Default values
|
||||
BUILD_MODE=linux
|
||||
TARGET_ARCH=aarch64
|
||||
ARCH_BITS=64
|
||||
CLI_SDK_ROOT=""
|
||||
CLI_TOOLCHAIN_FILE=""
|
||||
|
||||
# Parse arguments
|
||||
while getopts 'm:a:b:s:t:h' opt; do
|
||||
case "$opt" in
|
||||
m)
|
||||
BUILD_MODE=$OPTARG
|
||||
;;
|
||||
a)
|
||||
TARGET_ARCH=$OPTARG
|
||||
;;
|
||||
b)
|
||||
ARCH_BITS=$OPTARG
|
||||
;;
|
||||
s)
|
||||
CLI_SDK_ROOT=$OPTARG
|
||||
;;
|
||||
t)
|
||||
CLI_TOOLCHAIN_FILE=$OPTARG
|
||||
;;
|
||||
h)
|
||||
usage
|
||||
;;
|
||||
*)
|
||||
usage
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
ROOT_PWD=$(cd "$(dirname $0)" && pwd)
|
||||
|
||||
# ===========================================================================
|
||||
# Yocto build
|
||||
# ===========================================================================
|
||||
if [[ "${BUILD_MODE}" == "yocto" ]]; then
|
||||
|
||||
if [[ "${ARCH_BITS}" != "32" && "${ARCH_BITS}" != "64" ]]; then
|
||||
echo "Unsupported ARCH_BITS \"${ARCH_BITS}\". Must be 32 or 64." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Configurable via environment variables (CLI args > env vars > defaults)
|
||||
CMAKE_BIN="${CMAKE_BIN:-cmake}"
|
||||
YOCTO_SDK_ROOT="${CLI_SDK_ROOT:-${YOCTO_SDK_ROOT:-/data/yuandian/tools/poky/4.0.20}}"
|
||||
TOOLCHAIN_FILE="${CLI_TOOLCHAIN_FILE:-${TOOLCHAIN_FILE:-${ROOT_PWD}/../../cmake/yocto-toolchain.cmake}}"
|
||||
|
||||
# Export variables for CMake
|
||||
export YOCTO_SDK_ROOT
|
||||
export ARCH_BITS
|
||||
|
||||
BUILD_DIR="${ROOT_PWD}/build/yocto/${ARCH_BITS}"
|
||||
|
||||
echo "==> Building Yocto ${ARCH_BITS}-bit"
|
||||
echo " toolchain : ${TOOLCHAIN_FILE}"
|
||||
echo " SDK root : ${YOCTO_SDK_ROOT}"
|
||||
echo " BUILD_DIR : ${BUILD_DIR}"
|
||||
|
||||
mkdir -p "${BUILD_DIR}"
|
||||
rm -rf "${BUILD_DIR}"
|
||||
|
||||
# Select OpenCV based on target architecture
|
||||
if [[ "${ARCH_BITS}" == "32" ]]; then
|
||||
OPENCV_DIR="${ROOT_PWD}/../../../dependency/opencv/opencv-linux-armhf/share/OpenCV"
|
||||
else
|
||||
OPENCV_DIR="${ROOT_PWD}/../../../dependency/opencv/opencv-linux-aarch64/share/OpenCV"
|
||||
fi
|
||||
|
||||
"${CMAKE_BIN}" \
|
||||
-S "${ROOT_PWD}/src" \
|
||||
-B "${BUILD_DIR}" \
|
||||
-DCMAKE_TOOLCHAIN_FILE="${TOOLCHAIN_FILE}" \
|
||||
-DYOCTO_SDK_ROOT="${YOCTO_SDK_ROOT}" \
|
||||
-DARCH_BITS="${ARCH_BITS}" \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DOpenCV_DIR="${OPENCV_DIR}"
|
||||
|
||||
"${CMAKE_BIN}" --build "${BUILD_DIR}" --config Release
|
||||
|
||||
# Strip (best-effort)
|
||||
HOST_SYSROOT="${YOCTO_SDK_ROOT}/sysroots/x86_64-pokysdk-linux"
|
||||
if [[ "${ARCH_BITS}" == "32" ]]; then
|
||||
CROSS_TRIPLE="arm-poky-linux-gnueabi"
|
||||
else
|
||||
CROSS_TRIPLE="aarch64-poky-linux"
|
||||
fi
|
||||
STRIP_TOOL="${HOST_SYSROOT}/usr/bin/${CROSS_TRIPLE}/${CROSS_TRIPLE}-strip"
|
||||
if [[ -x "${STRIP_TOOL}" ]]; then
|
||||
"${STRIP_TOOL}" --strip-unneeded "${BUILD_DIR}/blazepose_detect_demo"
|
||||
else
|
||||
echo "warning: strip tool not found; keeping debug info." >&2
|
||||
fi
|
||||
|
||||
echo "Build complete. Executable in ${BUILD_DIR}/blazepose_detect_demo"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# ===========================================================================
|
||||
# Standard Linux cross-compile build
|
||||
# ===========================================================================
|
||||
|
||||
# Default to aarch64-linux-gnu if GCC_COMPILER is not set
|
||||
GCC_COMPILER=${GCC_COMPILER:-aarch64-linux-gnu}
|
||||
|
||||
# Set compilers
|
||||
export CC=${GCC_COMPILER}-gcc
|
||||
export CXX=${GCC_COMPILER}-g++
|
||||
|
||||
# Validate compiler
|
||||
if ! command -v ${CC} &> /dev/null; then
|
||||
echo "Error: Compiler ${CC} not found."
|
||||
echo "Please set GCC_COMPILER environment variable to your cross-compiler path prefix."
|
||||
echo "Example: export GCC_COMPILER=/path/to/toolchain/bin/aarch64-linux-gnu"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
BUILD_DIR=${ROOT_PWD}/build/linux
|
||||
|
||||
echo "Building for Linux..."
|
||||
echo "COMPILER: ${CC}"
|
||||
echo "TARGET_ARCH: ${TARGET_ARCH}"
|
||||
echo "BUILD_DIR: ${BUILD_DIR}"
|
||||
|
||||
mkdir -p ${BUILD_DIR}
|
||||
cd ${BUILD_DIR}
|
||||
|
||||
cmake ../../src \
|
||||
-DCMAKE_SYSTEM_NAME=Linux \
|
||||
-DCMAKE_SYSTEM_PROCESSOR=${TARGET_ARCH} \
|
||||
-DCMAKE_BUILD_TYPE=Release
|
||||
|
||||
make -j4
|
||||
|
||||
echo "Build complete. Executable in ${BUILD_DIR}/blazepose_detect_demo"
|
||||
36
examples/blazepose_detect/cpp/src/CMakeLists.txt
Executable file
36
examples/blazepose_detect/cpp/src/CMakeLists.txt
Executable file
|
|
@ -0,0 +1,36 @@
|
|||
cmake_minimum_required(VERSION 3.10...3.27)
|
||||
project(blazepose_detect_demo)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/../../../../cmake")
|
||||
find_package(AMLNN REQUIRED)
|
||||
include_directories(${AMLNN_INCLUDE_DIR})
|
||||
link_directories(${AMLNN_LIBRARY_DIR})
|
||||
|
||||
include_directories(${CMAKE_SOURCE_DIR}/../../../../common)
|
||||
|
||||
# Set 3rdparty path
|
||||
set(3RDPARTY_DIR "${CMAKE_SOURCE_DIR}/../../../../dependency")
|
||||
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL "Android")
|
||||
# Android needs log
|
||||
link_libraries(log)
|
||||
endif()
|
||||
|
||||
# Find OpenCV
|
||||
message(STATUS "OpenCV_DIR: ${OpenCV_DIR}")
|
||||
find_package(OpenCV REQUIRED)
|
||||
include_directories(${OpenCV_INCLUDE_DIRS})
|
||||
|
||||
add_executable(blazepose_detect_demo
|
||||
main.cpp
|
||||
postprocess.cpp
|
||||
postprocess.h
|
||||
${CMAKE_SOURCE_DIR}/../../../../common/model_loader.cpp
|
||||
)
|
||||
|
||||
target_link_libraries(blazepose_detect_demo
|
||||
${OpenCV_LIBS}
|
||||
${AMLNN_LIBRARY}
|
||||
)
|
||||
2278
examples/blazepose_detect/cpp/src/anchors.h
Executable file
2278
examples/blazepose_detect/cpp/src/anchors.h
Executable file
File diff suppressed because it is too large
Load diff
151
examples/blazepose_detect/cpp/src/main.cpp
Executable file
151
examples/blazepose_detect/cpp/src/main.cpp
Executable file
|
|
@ -0,0 +1,151 @@
|
|||
/*
|
||||
* Copyright (C) 2024–2025 Amlogic, Inc. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <chrono>
|
||||
#include <tuple>
|
||||
#include <iomanip>
|
||||
#include <fstream>
|
||||
#include <opencv2/opencv.hpp>
|
||||
#include "postprocess.h"
|
||||
#include "model_loader.h"
|
||||
|
||||
const std::string DEFAULT_OUTPUT_PATH = "./result.jpg";
|
||||
const int MODEL_INPUT_WIDTH = 224;
|
||||
const int MODEL_INPUT_HEIGHT = 224;
|
||||
const float SCORE_THRESHOLD = 0.5f;
|
||||
const float NMS_THRESHOLD = 0.3f;
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
std::string model_path;
|
||||
std::string image_path;
|
||||
|
||||
if (argc != 3)
|
||||
{
|
||||
printf("%s <model_path> <image_path>\n", argv[0]);
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (argc > 1)
|
||||
model_path = argv[1];
|
||||
if (argc > 2)
|
||||
image_path = argv[2];
|
||||
|
||||
std::cout << "Blazepose Detect Demo" << std::endl;
|
||||
std::cout << "Model: " << model_path << std::endl;
|
||||
std::cout << "Image: " << image_path << std::endl;
|
||||
std::cout << "Output: " << DEFAULT_OUTPUT_PATH << std::endl;
|
||||
|
||||
// 1. Load Image
|
||||
cv::Mat img = cv::imread(image_path);
|
||||
if (img.empty())
|
||||
{
|
||||
std::cerr << "Failed to load image from " << image_path << std::endl;
|
||||
return -1;
|
||||
}
|
||||
|
||||
// 2. Initialize Network
|
||||
void *context = init_network(model_path.c_str());
|
||||
if (!context)
|
||||
{
|
||||
std::cerr << "Failed to initialize network." << std::endl;
|
||||
return -1;
|
||||
}
|
||||
|
||||
// 3. Preprocess
|
||||
auto start_time = std::chrono::high_resolution_clock::now();
|
||||
|
||||
auto [preprocessed, scale, pad] = preprocess(img, std::make_tuple(MODEL_INPUT_HEIGHT, MODEL_INPUT_WIDTH));
|
||||
std::cout << "scale" << scale << std::endl;
|
||||
std::cout << "pad: ("
|
||||
<< std::get<0>(pad) << ", "
|
||||
<< std::get<1>(pad) << ")"
|
||||
<< std::endl;
|
||||
// Quantize to int8 (model expects quantized input)
|
||||
cv::Mat quantized_img = quantize_input(preprocessed, 0.007843137718737125, -1);
|
||||
|
||||
// 4. Set input and run inference
|
||||
nn_input inData;
|
||||
memset(&inData, 0, sizeof(nn_input));
|
||||
inData.input_type = BINARY_RAW_DATA;
|
||||
inData.input = quantized_img.data;
|
||||
inData.input_index = 0;
|
||||
inData.size = quantized_img.total() * quantized_img.elemSize();
|
||||
|
||||
if (aml_module_input_set(context, &inData) != 0)
|
||||
{
|
||||
std::cerr << "Failed to set input." << std::endl;
|
||||
uninit_network(context);
|
||||
return -1;
|
||||
}
|
||||
|
||||
aml_output_config_t outconfig;
|
||||
memset(&outconfig, 0, sizeof(aml_output_config_t));
|
||||
outconfig.typeSize = sizeof(aml_output_config_t);
|
||||
outconfig.format = AML_OUTDATA_FLOAT32;
|
||||
|
||||
nn_output *outdata = (nn_output *)aml_module_output_get(context, outconfig);
|
||||
if (!outdata)
|
||||
{
|
||||
std::cerr << "Failed to run network." << std::endl;
|
||||
uninit_network(context);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// 5. Postprocess
|
||||
float *ori_boxes = (float *)outdata->out[0].buf; // 2254 * 12
|
||||
float *raw_scores = (float *)outdata->out[1].buf; // 2254 * 1
|
||||
|
||||
std::vector<BlazePoseDetection> detections = postprocess(
|
||||
ori_boxes,
|
||||
raw_scores,
|
||||
std::make_tuple(preprocessed, scale, pad),
|
||||
SCORE_THRESHOLD,
|
||||
NMS_THRESHOLD);
|
||||
|
||||
auto end_time = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double, std::milli> inference_time = end_time - start_time;
|
||||
|
||||
std::cout << "Inference time: " << inference_time.count() << " ms" << std::endl;
|
||||
std::cout << "Detections: " << detections.size() << std::endl;
|
||||
|
||||
// 6. Draw and Save
|
||||
cv::Mat result_img = draw_detections(img, detections);
|
||||
cv::imwrite(DEFAULT_OUTPUT_PATH, result_img);
|
||||
std::cout << "Result saved to " << DEFAULT_OUTPUT_PATH << std::endl;
|
||||
|
||||
// image_path -> txt_path
|
||||
std::string txt_path = image_path.substr(0, image_path.find_last_of('.'));
|
||||
txt_path += ".txt";
|
||||
std::ofstream ofs(txt_path);
|
||||
if (ofs.is_open())
|
||||
{
|
||||
for (const auto &det : detections)
|
||||
{
|
||||
for (int i = 0; i < NUM_COORDS + 1; ++i)
|
||||
ofs << det.coords[i] << (i < NUM_COORDS ? " " : "\n");
|
||||
}
|
||||
}
|
||||
std::cout << "Detections saved to " << txt_path << std::endl;
|
||||
|
||||
// 7. Cleanup
|
||||
uninit_network(context);
|
||||
|
||||
return 0;
|
||||
}
|
||||
306
examples/blazepose_detect/cpp/src/postprocess.cpp
Executable file
306
examples/blazepose_detect/cpp/src/postprocess.cpp
Executable file
|
|
@ -0,0 +1,306 @@
|
|||
/*
|
||||
* Copyright (C) 2024–2025 Amlogic, Inc. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include "postprocess.h"
|
||||
#include <iostream>
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
#include <unordered_map>
|
||||
|
||||
#define LOGI(...) \
|
||||
do \
|
||||
{ \
|
||||
printf(__VA_ARGS__); \
|
||||
printf("\n"); \
|
||||
} while (0)
|
||||
#define LOGE(...) \
|
||||
do \
|
||||
{ \
|
||||
fprintf(stderr, __VA_ARGS__); \
|
||||
fprintf(stderr, "\n"); \
|
||||
} while (0)
|
||||
|
||||
// SHOW class names (1 classes)
|
||||
const char *SHOW_CLASSES[1] = {"pose"};
|
||||
|
||||
inline float sigmoid(float x)
|
||||
{
|
||||
return 1.0f / (1.0f + std::exp(-x));
|
||||
}
|
||||
|
||||
void decode_boxes(const float *ori_boxes, std::vector<std::vector<float>> &boxes)
|
||||
{
|
||||
const float x_scale = 224.0f;
|
||||
const float y_scale = 224.0f;
|
||||
const float h_scale = 224.0f;
|
||||
const float w_scale = 224.0f;
|
||||
boxes.resize(NUM_ANCHORS, std::vector<float>(NUM_COORDS, 0.0f));
|
||||
for (int i = 0; i < NUM_ANCHORS; ++i)
|
||||
{
|
||||
float x_center = ori_boxes[i * NUM_COORDS + 0] / x_scale * anchors[i * 4 + 2] + anchors[i * 4 + 0];
|
||||
float y_center = ori_boxes[i * NUM_COORDS + 1] / y_scale * anchors[i * 4 + 3] + anchors[i * 4 + 1];
|
||||
float w = ori_boxes[i * NUM_COORDS + 2] / w_scale * anchors[i * 4 + 2];
|
||||
float h = ori_boxes[i * NUM_COORDS + 3] / h_scale * anchors[i * 4 + 3];
|
||||
boxes[i][0] = y_center - h / 2.0f;
|
||||
boxes[i][1] = x_center - w / 2.0f;
|
||||
boxes[i][2] = y_center + h / 2.0f;
|
||||
boxes[i][3] = x_center + w / 2.0f;
|
||||
for (int k = 0; k < 4; ++k)
|
||||
{
|
||||
int offset = 4 + k * 2;
|
||||
float keypoint_x = ori_boxes[i * NUM_COORDS + offset] / x_scale * anchors[i * 4 + 2] + anchors[i * 4 + 0];
|
||||
float keypoint_y = ori_boxes[i * NUM_COORDS + offset + 1] / y_scale * anchors[i * 4 + 3] + anchors[i * 4 + 1];
|
||||
boxes[i][offset] = keypoint_x;
|
||||
boxes[i][offset + 1] = keypoint_y;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void convert_output_to_detections(const float *ori_boxes, const float *ori_scores, std::vector<BlazePoseDetection> &detections, float min_score_thresh = 0.3f)
|
||||
{
|
||||
std::vector<std::vector<float>> decoded_boxes;
|
||||
decode_boxes(ori_boxes, decoded_boxes);
|
||||
detections.clear();
|
||||
for (int i = 0; i < NUM_ANCHORS; ++i)
|
||||
{
|
||||
float s = sigmoid(std::min(std::max(ori_scores[i], -100.0f), 100.0f));
|
||||
if (s < min_score_thresh)
|
||||
continue;
|
||||
BlazePoseDetection det;
|
||||
for (int j = 0; j < NUM_COORDS; ++j)
|
||||
det.coords[j] = decoded_boxes[i][j];
|
||||
det.coords[NUM_COORDS] = s;
|
||||
detections.push_back(det);
|
||||
}
|
||||
}
|
||||
|
||||
static inline float iou(const float *a, const float *b)
|
||||
{
|
||||
float xA = std::max(a[1], b[1]);
|
||||
float yA = std::max(a[0], b[0]);
|
||||
float xB = std::min(a[3], b[3]);
|
||||
float yB = std::min(a[2], b[2]);
|
||||
float interW = std::max(0.0f, xB - xA);
|
||||
float interH = std::max(0.0f, yB - yA);
|
||||
float inter = interW * interH;
|
||||
float areaA = (a[3] - a[1]) * (a[2] - a[0]);
|
||||
float areaB = (b[3] - b[1]) * (b[2] - b[0]);
|
||||
float unionAB = areaA + areaB - inter;
|
||||
if (unionAB <= 0.0f)
|
||||
return 0.0f;
|
||||
return inter / unionAB;
|
||||
}
|
||||
|
||||
void weighted_nms(
|
||||
std::vector<BlazePoseDetection> &detections, std::vector<BlazePoseDetection> &output, float iou_threshold = 0.3f)
|
||||
{
|
||||
output.clear();
|
||||
if (detections.empty())
|
||||
return;
|
||||
std::sort(detections.begin(), detections.end(),
|
||||
[](const BlazePoseDetection &a, const BlazePoseDetection &b)
|
||||
{
|
||||
return a.coords[NUM_COORDS] > b.coords[NUM_COORDS];
|
||||
});
|
||||
std::vector<bool> removed(detections.size(), false);
|
||||
for (size_t i = 0; i < detections.size(); ++i)
|
||||
{
|
||||
if (removed[i])
|
||||
continue;
|
||||
std::vector<size_t> overlap_indices;
|
||||
overlap_indices.push_back(i);
|
||||
for (size_t j = i + 1; j < detections.size(); ++j)
|
||||
{
|
||||
if (removed[j])
|
||||
continue;
|
||||
if (iou(detections[i].coords, detections[j].coords) > iou_threshold)
|
||||
overlap_indices.push_back(j);
|
||||
}
|
||||
float total_score = 0.0f;
|
||||
std::vector<float> weighted(NUM_COORDS, 0.0f);
|
||||
for (size_t idx : overlap_indices)
|
||||
{
|
||||
float score = detections[idx].coords[NUM_COORDS];
|
||||
total_score += score;
|
||||
for (int k = 0; k < NUM_COORDS; ++k)
|
||||
weighted[k] += detections[idx].coords[k] * score;
|
||||
removed[idx] = true;
|
||||
}
|
||||
BlazePoseDetection wdet;
|
||||
for (int k = 0; k < NUM_COORDS; ++k)
|
||||
wdet.coords[k] = weighted[k] / total_score;
|
||||
wdet.coords[NUM_COORDS] = total_score / overlap_indices.size();
|
||||
output.push_back(wdet);
|
||||
}
|
||||
}
|
||||
|
||||
std::tuple<cv::Mat, float, std::tuple<int, int>> preprocess(cv::Mat img, std::tuple<int, int> new_shape)
|
||||
{
|
||||
cv::Mat img_rgb;
|
||||
|
||||
if (img.empty())
|
||||
{
|
||||
LOGE("Preprocess received empty image");
|
||||
return {};
|
||||
}
|
||||
|
||||
// Convert to RGB
|
||||
if (img.channels() == 4)
|
||||
cv::cvtColor(img, img_rgb, cv::COLOR_RGBA2RGB);
|
||||
else if (img.channels() == 3)
|
||||
cv::cvtColor(img, img_rgb, cv::COLOR_BGR2RGB);
|
||||
else
|
||||
img_rgb = img.clone();
|
||||
|
||||
int orig_h = img.rows;
|
||||
int orig_w = img.cols;
|
||||
float scale = std::min(static_cast<float>(std::get<0>(new_shape)) / orig_h,
|
||||
static_cast<float>(std::get<1>(new_shape)) / orig_w);
|
||||
int new_h = static_cast<int>(round(orig_h * scale));
|
||||
int new_w = static_cast<int>(round(orig_w * scale));
|
||||
|
||||
cv::Mat img_resized;
|
||||
cv::resize(img_rgb, img_resized, cv::Size(new_w, new_h), 0, 0, cv::INTER_LINEAR);
|
||||
|
||||
int pad_h = std::get<0>(new_shape) - new_h;
|
||||
int pad_w = std::get<1>(new_shape) - new_w;
|
||||
int pad_left = static_cast<int>(round(pad_w / 2.0 - 0.1));
|
||||
int pad_right = static_cast<int>(round(pad_w / 2.0 + 0.1));
|
||||
int pad_top = static_cast<int>(round(pad_h / 2.0 - 0.1));
|
||||
int pad_bottom = static_cast<int>(round(pad_h / 2.0 + 0.1));
|
||||
|
||||
cv::Mat img_padded;
|
||||
cv::copyMakeBorder(img_resized, img_padded, pad_top, pad_bottom, pad_left, pad_right, cv::BORDER_CONSTANT, cv::Scalar(0, 0, 0));
|
||||
|
||||
cv::Mat img_float;
|
||||
img_padded.convertTo(img_float, CV_32F, 1.0 / 127.5, -1.0);
|
||||
|
||||
scale = 1.0f / scale;
|
||||
int pad_orig_h = static_cast<int>(pad_top * scale);
|
||||
int pad_orig_w = static_cast<int>(pad_left * scale);
|
||||
|
||||
return std::make_tuple(img_float, scale, std::make_tuple(pad_orig_h, pad_orig_w));
|
||||
}
|
||||
|
||||
cv::Mat quantize_input(const cv::Mat &float_img, float scale, int8_t zero_point)
|
||||
{
|
||||
if (float_img.empty() || float_img.type() != CV_32FC3)
|
||||
{
|
||||
LOGE("quantize_input: Invalid input image (must be CV_32FC3)");
|
||||
return cv::Mat();
|
||||
}
|
||||
|
||||
cv::Mat quantized_img(float_img.rows, float_img.cols, CV_8SC3);
|
||||
const float *src_ptr = (const float *)float_img.data;
|
||||
int8_t *dst_ptr = (int8_t *)quantized_img.data;
|
||||
|
||||
int total_elements = float_img.total() * float_img.channels();
|
||||
for (int i = 0; i < total_elements; ++i)
|
||||
{
|
||||
dst_ptr[i] = static_cast<int8_t>(std::round(src_ptr[i] / scale + zero_point));
|
||||
}
|
||||
|
||||
return quantized_img;
|
||||
}
|
||||
|
||||
void denorm_detections(std::vector<float> &detection, float scale, const float pad[2])
|
||||
{
|
||||
detection[0] = detection[0] * scale * 224.0f - pad[0];
|
||||
detection[1] = detection[1] * scale * 224.0f - pad[1];
|
||||
detection[2] = detection[2] * scale * 224.0f - pad[0];
|
||||
detection[3] = detection[3] * scale * 224.0f - pad[1];
|
||||
|
||||
for (size_t k = 4; k + 1 < detection.size(); k += 2)
|
||||
{
|
||||
detection[k] = detection[k] * scale * 224.0f - pad[1];
|
||||
detection[k + 1] = detection[k + 1] * scale * 224.0f - pad[0];
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<BlazePoseDetection> postprocess(float *ori_boxes, float *ori_scores,
|
||||
std::tuple<cv::Mat, float, std::tuple<int, int>> input_tuple,
|
||||
float conf_threshold, float iou_threshold)
|
||||
{
|
||||
float scale = std::get<1>(input_tuple);
|
||||
int pad_left = std::get<0>(std::get<2>(input_tuple));
|
||||
int pad_top = std::get<1>(std::get<2>(input_tuple));
|
||||
float pad[2] = {static_cast<float>(pad_left), static_cast<float>(pad_top)};
|
||||
|
||||
std::vector<BlazePoseDetection> detections;
|
||||
convert_output_to_detections(ori_boxes, ori_scores, detections, conf_threshold);
|
||||
|
||||
std::vector<BlazePoseDetection> filtered;
|
||||
weighted_nms(detections, filtered, iou_threshold);
|
||||
|
||||
int pose_num = filtered.size();
|
||||
for (size_t b = 0; b < pose_num; ++b)
|
||||
{
|
||||
std::vector<float> coords(filtered[b].coords, filtered[b].coords + NUM_COORDS + 1);
|
||||
// mapping to original size
|
||||
denorm_detections(coords, scale, pad);
|
||||
for (size_t i = 0; i < NUM_COORDS + 1; ++i)
|
||||
filtered[b].coords[i] = coords[i];
|
||||
}
|
||||
|
||||
return filtered;
|
||||
}
|
||||
|
||||
cv::Mat draw_detections(cv::Mat image, const std::vector<BlazePoseDetection> &detections)
|
||||
{
|
||||
cv::Mat drawn_image = image.clone();
|
||||
int class_id = 0;
|
||||
for (const auto &det : detections)
|
||||
{
|
||||
// Generate color based on class_id using HSV
|
||||
float hue = fmod(class_id * 137.508f, 360.0f);
|
||||
cv::Mat hsv(1, 1, CV_8UC3, cv::Scalar(hue / 2.0f, 204, 230));
|
||||
cv::Mat rgb;
|
||||
cv::cvtColor(hsv, rgb, cv::COLOR_HSV2BGR);
|
||||
cv::Scalar color(rgb.at<cv::Vec3b>(0, 0)[0], rgb.at<cv::Vec3b>(0, 0)[1], rgb.at<cv::Vec3b>(0, 0)[2]);
|
||||
|
||||
// Draw bounding box
|
||||
int x1 = static_cast<int>(det.coords[1]);
|
||||
int y1 = static_cast<int>(det.coords[0]);
|
||||
int x2 = static_cast<int>(det.coords[3]);
|
||||
int y2 = static_cast<int>(det.coords[2]);
|
||||
cv::rectangle(drawn_image, cv::Point(x1, y1), cv::Point(x2, y2), color, 2);
|
||||
|
||||
// Draw label
|
||||
std::string label = std::string(SHOW_CLASSES[class_id]) + ": " + cv::format("%.2f", det.coords[12]);
|
||||
int baseline = 0;
|
||||
cv::Size text_size = cv::getTextSize(label, cv::FONT_HERSHEY_SIMPLEX, 0.6, 1, &baseline);
|
||||
|
||||
int label_x = x1;
|
||||
int label_y = y1 - 5;
|
||||
if (label_y < text_size.height)
|
||||
label_y = x1 + text_size.height + 5;
|
||||
|
||||
// Draw label background
|
||||
cv::rectangle(drawn_image,
|
||||
cv::Point(label_x, label_y - text_size.height - baseline),
|
||||
cv::Point(label_x + text_size.width, label_y + baseline),
|
||||
color, cv::FILLED);
|
||||
|
||||
// Determine text color based on background brightness
|
||||
int brightness = (color[0] + color[1] + color[2]) / 3;
|
||||
cv::Scalar text_color = brightness < 128 ? cv::Scalar(255, 255, 255) : cv::Scalar(0, 0, 0);
|
||||
|
||||
cv::putText(drawn_image, label,
|
||||
cv::Point(label_x, label_y),
|
||||
cv::FONT_HERSHEY_SIMPLEX, 0.6, text_color, 1, cv::LINE_AA);
|
||||
}
|
||||
return drawn_image;
|
||||
}
|
||||
52
examples/blazepose_detect/cpp/src/postprocess.h
Executable file
52
examples/blazepose_detect/cpp/src/postprocess.h
Executable file
|
|
@ -0,0 +1,52 @@
|
|||
/*
|
||||
* Copyright (C) 2024–2025 Amlogic, Inc. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef _AMLNN_BLAZEPOSE_DETECT_POSTPROCESS_H_
|
||||
#define _AMLNN_BLAZEPOSE_DETECT_POSTPROCESS_H_
|
||||
|
||||
#include <opencv2/opencv.hpp>
|
||||
#include <vector>
|
||||
#include <tuple>
|
||||
#include <string>
|
||||
|
||||
#include "anchors.h"
|
||||
|
||||
#define NUM_COORDS 12
|
||||
|
||||
// BlazePoseDetection result structure
|
||||
struct BlazePoseDetection
|
||||
{
|
||||
float coords[NUM_COORDS + 1]; // 12 coords + 1 score
|
||||
};
|
||||
|
||||
// COCO class names (80 classes)
|
||||
extern const char *COCO_CLASSES[80];
|
||||
|
||||
// Preprocess image with letterbox resizing
|
||||
std::tuple<cv::Mat, float, std::tuple<int, int>> preprocess(cv::Mat img, std::tuple<int, int> new_shape);
|
||||
|
||||
// Quantize float32 image to int8 for model input
|
||||
cv::Mat quantize_input(const cv::Mat &float_img, float scale = 0.007843137718737125, int8_t zero_point = -1);
|
||||
|
||||
// Postprocess blazepose_detect outputs with DFL decoding
|
||||
std::vector<BlazePoseDetection> postprocess(float *raw_boxes, float *raw_scores,
|
||||
std::tuple<cv::Mat, float, std::tuple<int, int>> input_tuple,
|
||||
float conf_threshold, float iou_threshold);
|
||||
|
||||
// Draw detections on image
|
||||
cv::Mat draw_detections(cv::Mat image, const std::vector<BlazePoseDetection> &detections);
|
||||
|
||||
#endif // _AMLNN_BLAZEPOSE_DETECT_POSTPROCESS_H_
|
||||
0
examples/blazepose_detect/model/.gitkeep
Normal file → Executable file
0
examples/blazepose_detect/model/.gitkeep
Normal file → Executable file
40
examples/blazepose_detect/model/adla_convert.sh
Executable file
40
examples/blazepose_detect/model/adla_convert.sh
Executable file
|
|
@ -0,0 +1,40 @@
|
|||
#
|
||||
# Copyright (C) 2026 Amlogic, Inc. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
# 1. $1: set ADLA_TOOL_PATH
|
||||
# 2. $2: set target-platform
|
||||
# for A311D2 target-platform is PRODUCT_PID0XA003
|
||||
# for S905X5 target-platform is PRODUCT_PID0XA005
|
||||
# Usage: ./adla_convert.sh pose_detection.tflite /XXX/adla-toolkit-binary-3.2.9.3 PRODUCT_PID0XA005
|
||||
|
||||
model_path=$1
|
||||
ADLA_TOOL_PATH=$2
|
||||
target_platform=$3
|
||||
|
||||
echo "model_path:[$model_path]"
|
||||
echo "ADLA_TOOL_PATH:[$ADLA_TOOL_PATH]"
|
||||
echo "target-platform:[$target_platform]"
|
||||
|
||||
adla_convert=${ADLA_TOOL_PATH}/bin/adla_convert
|
||||
|
||||
$adla_convert --model-type tflite \
|
||||
--model $model_path \
|
||||
--inputs input_1 --input-shapes "224,224,3" \
|
||||
--quantize-dtype int8 \
|
||||
--source-file dataset_coco.txt \
|
||||
--channel-mean-value "127.5,127.5,127.5,127.5" \
|
||||
--target-platform $target_platform \
|
||||
--disable-per-channel false
|
||||
50
examples/blazepose_detect/model/dataset_coco.txt
Executable file
50
examples/blazepose_detect/model/dataset_coco.txt
Executable file
|
|
@ -0,0 +1,50 @@
|
|||
../../../resource/coco_dataset/000000000139.jpg
|
||||
../../../resource/coco_dataset/000000000285.jpg
|
||||
../../../resource/coco_dataset/000000000632.jpg
|
||||
../../../resource/coco_dataset/000000000724.jpg
|
||||
../../../resource/coco_dataset/000000000776.jpg
|
||||
../../../resource/coco_dataset/000000000785.jpg
|
||||
../../../resource/coco_dataset/000000000802.jpg
|
||||
../../../resource/coco_dataset/000000000872.jpg
|
||||
../../../resource/coco_dataset/000000000885.jpg
|
||||
../../../resource/coco_dataset/000000001000.jpg
|
||||
../../../resource/coco_dataset/000000001268.jpg
|
||||
../../../resource/coco_dataset/000000001296.jpg
|
||||
../../../resource/coco_dataset/000000001353.jpg
|
||||
../../../resource/coco_dataset/000000001425.jpg
|
||||
../../../resource/coco_dataset/000000001490.jpg
|
||||
../../../resource/coco_dataset/000000001503.jpg
|
||||
../../../resource/coco_dataset/000000001532.jpg
|
||||
../../../resource/coco_dataset/000000001584.jpg
|
||||
../../../resource/coco_dataset/000000001675.jpg
|
||||
../../../resource/coco_dataset/000000001761.jpg
|
||||
../../../resource/coco_dataset/000000001818.jpg
|
||||
../../../resource/coco_dataset/000000001993.jpg
|
||||
../../../resource/coco_dataset/000000002006.jpg
|
||||
../../../resource/coco_dataset/000000002149.jpg
|
||||
../../../resource/coco_dataset/000000002153.jpg
|
||||
../../../resource/coco_dataset/000000002157.jpg
|
||||
../../../resource/coco_dataset/000000002261.jpg
|
||||
../../../resource/coco_dataset/000000002299.jpg
|
||||
../../../resource/coco_dataset/000000002431.jpg
|
||||
../../../resource/coco_dataset/000000002473.jpg
|
||||
../../../resource/coco_dataset/000000002532.jpg
|
||||
../../../resource/coco_dataset/000000002587.jpg
|
||||
../../../resource/coco_dataset/000000002592.jpg
|
||||
../../../resource/coco_dataset/000000002685.jpg
|
||||
../../../resource/coco_dataset/000000002923.jpg
|
||||
../../../resource/coco_dataset/000000003156.jpg
|
||||
../../../resource/coco_dataset/000000003255.jpg
|
||||
../../../resource/coco_dataset/000000003501.jpg
|
||||
../../../resource/coco_dataset/000000003553.jpg
|
||||
../../../resource/coco_dataset/000000003661.jpg
|
||||
../../../resource/coco_dataset/000000003845.jpg
|
||||
../../../resource/coco_dataset/000000003934.jpg
|
||||
../../../resource/coco_dataset/000000004134.jpg
|
||||
../../../resource/coco_dataset/000000004395.jpg
|
||||
../../../resource/coco_dataset/000000004495.jpg
|
||||
../../../resource/coco_dataset/000000004765.jpg
|
||||
../../../resource/coco_dataset/000000004795.jpg
|
||||
../../../resource/coco_dataset/000000005001.jpg
|
||||
../../../resource/coco_dataset/000000005037.jpg
|
||||
../../../resource/coco_dataset/000000005060.jpg
|
||||
BIN
examples/blazepose_detect/model/test.png
Executable file
BIN
examples/blazepose_detect/model/test.png
Executable file
Binary file not shown.
|
After Width: | Height: | Size: 2.4 MiB |
0
examples/blazepose_detect/py/.gitkeep
Normal file → Executable file
0
examples/blazepose_detect/py/.gitkeep
Normal file → Executable file
266
examples/blazepose_detect/py/balzepose_detect.py
Executable file
266
examples/blazepose_detect/py/balzepose_detect.py
Executable file
|
|
@ -0,0 +1,266 @@
|
|||
#
|
||||
# Copyright (C) 2026 Amlogic, Inc. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
import numpy as np
|
||||
import os
|
||||
import glob
|
||||
import argparse
|
||||
import cv2
|
||||
from pathlib import Path
|
||||
from amlnnlite.api import AMLNNLite
|
||||
|
||||
def letterbox(img, new_shape=(224, 224), color=(0, 0, 0)):
|
||||
shape = img.shape[:2] # [height, width]
|
||||
scale = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
|
||||
new_unpad = (int(round(shape[1] * scale)), int(round(shape[0] * scale)))
|
||||
pad_w = (new_shape[1] - new_unpad[0]) / 2
|
||||
pad_h = (new_shape[0] - new_unpad[1]) / 2
|
||||
|
||||
if shape[::-1] != new_unpad:
|
||||
img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
|
||||
|
||||
top, bottom = int(round(pad_h - 0.1)), int(round(pad_h + 0.1))
|
||||
left, right = int(round(pad_w - 0.1)), int(round(pad_w + 0.1))
|
||||
img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)
|
||||
|
||||
scale = 1. / scale
|
||||
ori_left = left * scale
|
||||
ori_top = top * scale
|
||||
return img, scale, (ori_left, ori_top)
|
||||
|
||||
def preprocess(img_path, new_shape=(224, 224), data_format='NCHW', s=0.003921568859368563, zp=-128):
|
||||
original_img = cv2.imread(str(img_path))
|
||||
if original_img is None:
|
||||
raise ValueError(f"can't read image: {img_path}")
|
||||
|
||||
processed_img, scale, pad = letterbox(original_img, new_shape)
|
||||
rgb_img = cv2.cvtColor(processed_img, cv2.COLOR_BGR2RGB)
|
||||
normalized_img = rgb_img.astype(np.float32) / 127.5 - 1.
|
||||
|
||||
if data_format == 'NCHW':
|
||||
# HWC -> CHW -> BCHW (ONNX default format)
|
||||
input_tensor = np.transpose(normalized_img, (2, 0, 1))
|
||||
input_tensor = np.expand_dims(input_tensor, axis=0)
|
||||
elif data_format == 'NHWC':
|
||||
# HWC -> BHWC (TFLITE default format)
|
||||
input_tensor = np.expand_dims(normalized_img, axis=0)
|
||||
else:
|
||||
raise ValueError(f"Unsupported data format: {data_format}. Only 'NCHW' and 'NHWC' are supported.")
|
||||
|
||||
# Quantize to int8
|
||||
input_tensor = np.round(input_tensor / s + zp).astype(np.int8)
|
||||
|
||||
return input_tensor, original_img, scale, pad
|
||||
|
||||
|
||||
def postprocess(outputs, scale, pad, data_format='NCHW', anchor_path='anchors.npy', score_threshold=0.5, nms_threshold=0.3):
|
||||
all_boxes = []
|
||||
all_scores = []
|
||||
|
||||
raw_box = outputs[0] # (1, 2254, 12)
|
||||
raw_score = outputs[1] # (1, 2254, 1)
|
||||
|
||||
anchors = np.load(anchor_path).astype("float32")
|
||||
|
||||
# all_boxes = decode_boxes(raw_box, anchors)
|
||||
# anchors: [N, 4] -> x, y, w, h
|
||||
anc_x, anc_y, anc_w, anc_h = anchors.T
|
||||
# raw_box shape: [..., K]
|
||||
all_boxes = np.zeros_like(raw_box)
|
||||
# box center & size
|
||||
x_center = raw_box[..., 0] / 224.0 * anc_w + anc_x
|
||||
y_center = raw_box[..., 1] / 224.0 * anc_h + anc_y
|
||||
w = raw_box[..., 2] / 224.0 * anc_w
|
||||
h = raw_box[..., 3] / 224.0 * anc_h
|
||||
# bbox: ymin, xmin, ymax, xmax
|
||||
all_boxes[..., 0] = y_center - 0.5 * h
|
||||
all_boxes[..., 1] = x_center - 0.5 * w
|
||||
all_boxes[..., 2] = y_center + 0.5 * h
|
||||
all_boxes[..., 3] = x_center + 0.5 * w
|
||||
# keypoints (4 points, each has x/y)
|
||||
for k in range(4):
|
||||
idx = 4 + k * 2
|
||||
all_boxes[..., idx] = raw_box[..., idx] / 224.0 * anc_w + anc_x
|
||||
all_boxes[..., idx + 1] = raw_box[..., idx + 1] / 224.0 * anc_h + anc_y
|
||||
|
||||
|
||||
thresh = 100.0
|
||||
raw_score = raw_score.clip(-thresh, thresh)
|
||||
# Apply sigmoid activation to class scores
|
||||
all_scores = 1.0 / (1.0 + np.exp(-raw_score)).squeeze(axis=-1)
|
||||
print(f"all_scores {all_scores}")
|
||||
print(f"max(all_scores) {max(all_scores[0])}")
|
||||
|
||||
mask = all_scores >= score_threshold
|
||||
|
||||
# Merge all scales
|
||||
final_boxes = np.concatenate(all_boxes, axis=0)
|
||||
final_scores = np.concatenate(all_scores, axis=0)
|
||||
|
||||
# Filter by confidence threshold
|
||||
valid_mask = final_scores > score_threshold
|
||||
if not np.any(valid_mask):
|
||||
return []
|
||||
|
||||
valid_boxes = final_boxes[valid_mask]
|
||||
valid_scores = final_scores[valid_mask]
|
||||
|
||||
# Map coordinates back to original image
|
||||
pad_x, pad_y = pad
|
||||
s = scale * 224
|
||||
valid_boxes[:, [0, 2]] = valid_boxes[:, [0, 2]] * s - pad_x
|
||||
valid_boxes[:, [1, 3]] = valid_boxes[:, [1, 3]] * s - pad_y
|
||||
valid_boxes[:, 4::2] = valid_boxes[:, 4::2] * s - pad_y
|
||||
valid_boxes[:, 5::2] = valid_boxes[:, 5::2] * s - pad_x
|
||||
valid_boxes = np.maximum(valid_boxes, 0)
|
||||
|
||||
# NMS
|
||||
if len(valid_boxes) > 0:
|
||||
nms_indices = cv2.dnn.NMSBoxes(
|
||||
valid_boxes.tolist(), valid_scores.tolist(), score_threshold, nms_threshold
|
||||
)
|
||||
|
||||
if len(nms_indices) > 0:
|
||||
nms_indices = nms_indices.flatten()
|
||||
detections = []
|
||||
|
||||
for idx in nms_indices:
|
||||
x1, y1, x2, y2 = valid_boxes[idx, :4]
|
||||
confidence = valid_scores[idx]
|
||||
|
||||
# x_center = (valid_boxes[:,1] + valid_boxes[:,3]) / 2
|
||||
# y_center = (valid_boxes[:,0] + valid_boxes[:,2]) / 2
|
||||
# scale = (valid_boxes[:,3] - valid_boxes[:,1]) # assumes square boxes
|
||||
|
||||
detections.append({
|
||||
'bbox': [float(x1), float(y1), float(x2), float(y2)],
|
||||
'confidence': float(confidence)
|
||||
})
|
||||
|
||||
return detections
|
||||
|
||||
return []
|
||||
|
||||
def get_class_color(class_id):
|
||||
import colorsys
|
||||
hue = (class_id * 137.508) % 360
|
||||
rgb = colorsys.hsv_to_rgb(hue/360.0, 0.8, 0.9)
|
||||
bgr = (int(rgb[2]*255), int(rgb[1]*255), int(rgb[0]*255))
|
||||
return bgr
|
||||
|
||||
def draw_detections(img, detections, save_path):
|
||||
result_img = img.copy()
|
||||
|
||||
for det in detections:
|
||||
x1, y1, x2, y2 = [int(coord) for coord in det['bbox']]
|
||||
confidence = det['confidence']
|
||||
class_name = det['class_name']
|
||||
class_id = det['class_id']
|
||||
|
||||
color = get_class_color(class_id)
|
||||
|
||||
cv2.rectangle(result_img, (x1, y1), (x2, y2), color, 2)
|
||||
|
||||
label = f"{class_name}: {confidence:.2f}"
|
||||
(label_w, label_h), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 1)
|
||||
cv2.rectangle(result_img, (x1, y1 - label_h - 10), (x1 + label_w, y1), color, -1)
|
||||
text_color = (255, 255, 255) if sum(color) < 400 else (0, 0, 0)
|
||||
cv2.putText(result_img, label, (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.6, text_color, 1)
|
||||
|
||||
cv2.imwrite(save_path, result_img)
|
||||
return result_img
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--model-path', default='./blazepose_detect_int8_A311D2.adla')
|
||||
parser.add_argument('--run-cycles', default= 1, type=int)
|
||||
args = parser.parse_args()
|
||||
|
||||
# Initialize AMLNNLite
|
||||
amlnn = AMLNNLite()
|
||||
amlnn.config(
|
||||
model_path=args.model_path, # Model file path, Support ADLA and quantized TFlite models
|
||||
run_cycles=args.run_cycles
|
||||
)
|
||||
amlnn.init()
|
||||
|
||||
# Find all image files in the 01_export_model directory
|
||||
image_dir = "./"
|
||||
image_extensions = ["*.jpg", "*.jpeg", "*.png", "*.bmp"]
|
||||
image_files = []
|
||||
for ext in image_extensions:
|
||||
image_files.extend(glob.glob(os.path.join(image_dir, ext)))
|
||||
image_files.extend(glob.glob(os.path.join(image_dir, ext.upper())))
|
||||
|
||||
if not image_files:
|
||||
print("No image files found in", image_dir)
|
||||
amlnn.uninit()
|
||||
return
|
||||
|
||||
print(f"Found {len(image_files)} image files to process:")
|
||||
for img_file in image_files:
|
||||
print(f" - {os.path.basename(img_file)}")
|
||||
print()
|
||||
|
||||
# Process each image
|
||||
for i, image_path in enumerate(image_files, 1):
|
||||
print(f"=" * 60)
|
||||
print(f"Processing image {i}/{len(image_files)}: {os.path.basename(image_path)}")
|
||||
print(f"=" * 60)
|
||||
|
||||
try:
|
||||
# Preprocess input
|
||||
input_tensor, original_img, scale, pad = preprocess(image_path, new_shape=(224, 224), data_format='NHWC', s=0.007843137718737125, zp=-1)
|
||||
|
||||
# Run inference
|
||||
outputs = amlnn.inference(inputs=[input_tensor])
|
||||
|
||||
# Postprocess results
|
||||
detections = postprocess(outputs, scale, pad, data_format='NHWC', score_threshold=0.5, nms_threshold=0.3)
|
||||
|
||||
# Print detection results
|
||||
if detections:
|
||||
print(f" Detected {len(detections)} objects:")
|
||||
for i, det in enumerate(detections, 1):
|
||||
print(f" {i}. {det['class_name']} ({det['confidence']:.2f})")
|
||||
else:
|
||||
print(" No objects detected")
|
||||
|
||||
# Save result image
|
||||
model_name = Path(args.model_path).stem
|
||||
result_dir = f"{model_name}_result"
|
||||
os.makedirs(result_dir, exist_ok=True)
|
||||
img_name = Path(image_path).stem
|
||||
save_path = os.path.join(result_dir, f"{img_name}_result.jpg")
|
||||
draw_detections(original_img, detections, str(save_path))
|
||||
print(f" Result saved to: {save_path}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error processing {os.path.basename(image_path)}: {e}")
|
||||
|
||||
print()
|
||||
|
||||
# Optional visualization
|
||||
amlnn.visualize()
|
||||
|
||||
# Release resources
|
||||
amlnn.uninit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
BIN
examples/blazepose_detect/result.jpg
Executable file
BIN
examples/blazepose_detect/result.jpg
Executable file
Binary file not shown.
|
After Width: | Height: | Size: 452 KiB |
Loading…
Add table
Add a link
Reference in a new issue