### Install C Sample Binaries Source: https://github.com/hyperinspire/inspireface/blob/master/cpp/sample/CMakeLists.txt Installs C sample executables to the specified runtime destination. Ensure the destination path is correctly set in your CMake configuration. ```cmake install(TARGETS Leak RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/sample) install(TARGETS FaceTrackSample RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/sample) install(TARGETS FaceComparisonSample RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/sample) install(TARGETS FaceCrudSample RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/sample) ``` -------------------------------- ### Install C++ Sample Binaries Source: https://github.com/hyperinspire/inspireface/blob/master/cpp/sample/CMakeLists.txt Installs C++ sample executables to the specified runtime destination. This is crucial for deploying the sample applications. ```cmake install(TARGETS CppSessionSample RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/sample) install(TARGETS CppFaceComparisonSample RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/sample) install(TARGETS CppFaceCrudSample RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/sample) ``` -------------------------------- ### Python SDK — Installation and Launch Source: https://context7.com/hyperinspire/inspireface/llms.txt Installs the SDK via pip and launches it, with automatic model download. `launch()` uses ModelScope by default; `use_oss_download(True)` can switch to OSS. `reload()` allows hot-swapping models. ```APIDOC ## Installation and Launch ### Description Provides instructions for installing the Python SDK using pip and launching it. It covers automatic model downloading, switching between download sources (ModelScope and OSS), and reloading models without restarting the application. ### Installation ```bash pip install -U inspireface ``` ### Launching the SDK ```python import inspireface as isf # Optional: Switch to OSS download if ModelScope is unavailable # isf.use_oss_download(True) # Download latest model weights before first use or after an SDK update isf.pull_latest_model("Pikachu") # lightweight, for edge/mobile isf.pull_latest_model("Megatron") # high-accuracy, for server/PC # Launch with a specific model (e.g., "Pikachu") # The SDK will auto-download the model if it's missing. ok = isf.launch("Pikachu") assert ok, "Launch failed" # Check SDK version and launch status print(f"Version: {isf.version()}") print(f"Launched: {isf.query_launch_status()}") # Switch to a different model without restarting isf.reload("Megatron") # Graceful shutdown isf.terminate() ``` ### Output Example ``` Version: 1.2.3 Launched: True ``` ``` -------------------------------- ### Install and Launch InspireFace Python SDK Source: https://context7.com/hyperinspire/inspireface/llms.txt Installs the InspireFace SDK via pip and launches it with automatic model download. Supports switching between ModelScope and OSS download sources and hot-swapping models. ```bash pip install -U inspireface ``` ```python import inspireface as isf # Optional: switch to OSS download if ModelScope is unavailable # isf.use_oss_download(True) # Pull latest model weights before first use (or after an SDK update) isf.pull_latest_model("Pikachu") # lightweight, for edge/mobile isf.pull_latest_model("Megatron") # high-accuracy, for server/PC # Launch with Pikachu (auto-downloads if missing) ok = isf.launch("Pikachu") assert ok, "Launch failed" print(f"Version: {isf.version()}") # e.g., "1.2.3" print(f"Launched: {isf.query_launch_status()}") # True # Switch to Megatron without restarting isf.reload("Megatron") # Graceful shutdown isf.terminate() # Output: # Version: 1.2.3 # Launched: True ``` -------------------------------- ### Android SDK Project Structure Example Source: https://github.com/hyperinspire/inspireface/blob/master/README.md Illustrates the expected directory structure for native libraries within an Android project. ```bash inspireface-android-sdk/inspireface/libs ├── arm64-v8a │ └── libInspireFace.so └── armeabi-v7a └── libInspireFace.so ``` -------------------------------- ### Face Detection and Landmark Drawing with InspireFace Source: https://github.com/hyperinspire/inspireface/blob/master/python/README.md A quick start example demonstrating face detection and drawing bounding boxes and landmarks on an image using the InspireFace Python API. Ensure OpenCV and the InspireFace library are installed and the dynamic library is correctly placed. ```python import cv2 import inspireface as isf # Create session with required features enabled session = isf.InspireFaceSession( opt=isf.HF_ENABLE_NONE, # Optional features detect_mode=isf.HF_DETECT_MODE_ALWAYS_DETECT # Detection mode ) # Set detection confidence threshold session.set_detection_confidence_threshold(0.5) # Read image image = cv2.imread("path/to/your/image.jpg") assert image is not None, "Please check if the image path is correct" # Perform face detection faces = session.face_detection(image) print(f"Detected {len(faces)} faces") # Draw detection results on image draw = image.copy() for idx, face in enumerate(faces): # Get face bounding box coordinates x1, y1, x2, y2 = face.location # Calculate rotated box parameters center = ((x1 + x2) / 2, (y1 + y2) / 2) size = (x2 - x1, y2 - y1) angle = face.roll # Draw rotated box rect = ((center[0], center[1]), (size[0], size[1]), angle) box = cv2.boxPoints(rect) box = box.astype(int) cv2.drawContours(draw, [box], 0, (100, 180, 29), 2) # Draw landmarks landmarks = session.get_face_dense_landmark(face) for x, y in landmarks.astype(int): cv2.circle(draw, (x, y), 0, (220, 100, 0), 2) ``` -------------------------------- ### Copy Dynamic Library for Manual Installation Source: https://github.com/hyperinspire/inspireface/blob/master/python/README.md Copy the compiled dynamic library to the correct system architecture directory for manual installation. ```bash # Copy the compiled dynamic library to the corresponding system architecture directory cp YOUR_BUILD_DIR/libInspireFace.so inspireface/modules/core/SYSTEM/CORE_ARCH/ ``` -------------------------------- ### Install Dependencies for InspireFace Source: https://github.com/hyperinspire/inspireface/blob/master/python/README.md Install the necessary Python dependencies before manual installation of the InspireFace package. ```bash pip install loguru tqdm opencv-python ``` -------------------------------- ### C/C++ Face Detection Example Source: https://github.com/hyperinspire/inspireface/blob/master/README.md Integrate InspireFace into C/C++ projects by linking the library and including headers. This example demonstrates face detection, mask detection, liveness detection, and quality detection. Ensure the resource file is loaded before use and free allocated memory at the end. ```c #include #include ... HResult ret; // The resource file must be loaded before it can be used ret = HFLaunchInspireFace(packPath); if (ret != HSUCCEED) { HFLogPrint(HF_LOG_ERROR, "Load Resource error: %d", ret); return ret; } // Enable the functions in the pipeline: mask detection, live detection, and face quality // detection HOption option = HF_ENABLE_QUALITY | HF_ENABLE_MASK_DETECT | HF_ENABLE_LIVENESS; // Non-video or frame sequence mode uses IMAGE-MODE, which is always face detection without // tracking HFDetectMode detMode = HF_DETECT_MODE_ALWAYS_DETECT; // Maximum number of faces detected HInt32 maxDetectNum = 20; // Face detection image input level HInt32 detectPixelLevel = 160; // Handle of the current face SDK algorithm context HFSession session = {0}; ret = HFCreateInspireFaceSessionOptional(option, detMode, maxDetectNum, detectPixelLevel, -1, &session); if (ret != HSUCCEED) { HFLogPrint(HF_LOG_ERROR, "Create FaceContext error: %d", ret); return ret; } // Configure some detection parameters HFSessionSetTrackPreviewSize(session, detectPixelLevel); HFSessionSetFilterMinimumFacePixelSize(session, 4); // Load a image HFImageBitmap image; ret = HFCreateImageBitmapFromFilePath(sourcePath, 3, &image); if (ret != HSUCCEED) { HFLogPrint(HF_LOG_ERROR, "The source entered is not a picture or read error."); return ret; } // Prepare an image parameter structure for configuration HFImageStream imageHandle = {0}; ret = HFCreateImageStreamFromImageBitmap(image, rotation_enum, &imageHandle); if (ret != HSUCCEED) { HFLogPrint(HF_LOG_ERROR, "Create ImageStream error: %d", ret); return ret; } // Execute HF_FaceContextRunFaceTrack captures face information in an image HFMultipleFaceData multipleFaceData = {0}; ret = HFExecuteFaceTrack(session, imageHandle, &multipleFaceData); if (ret != HSUCCEED) { HFLogPrint(HF_LOG_ERROR, "Execute HFExecuteFaceTrack error: %d", ret); return ret; } // Print the number of faces detected auto faceNum = multipleFaceData.detectedNum; HFLogPrint(HF_LOG_INFO, "Num of face: %d", faceNum); // The memory must be freed at the end of the program ret = HFReleaseImageBitmap(image); if (ret != HSUCCEED) { HFLogPrint(HF_LOG_ERROR, "Release image bitmap error: %d", ret); return ret; } ret = HFReleaseImageStream(imageHandle); if (ret != HSUCCEED) { HFLogPrint(HF_LOG_ERROR, "Release image stream error: %d", ret); } ret = HFReleaseInspireFaceSession(session); if (ret != HSUCCEED) { HFLogPrint(HF_LOG_ERROR, "Release session error: %d", ret); return ret; } ... ``` -------------------------------- ### Install InspireFace via pip Source: https://github.com/hyperinspire/inspireface/blob/master/python/README.md Use this command to install the latest release version of the InspireFace Python API. ```bash pip install inspireface ``` -------------------------------- ### Quick Test Script Source: https://github.com/hyperinspire/inspireface/blob/master/README.md Information on using provided scripts for a quick test setup, including automatic download of test files and building the test program. ```APIDOC ## Quick Test Script (Linux/Ubuntu) Execute the following script for a quick test on Ubuntu systems: ```bash bash ci/quick_test_linux_x86_usual.sh ``` ## Quick Test Script (Other Systems) Use this script for other systems, including Ubuntu, for a quick test setup: ```bash bash ci/quick_test_local.sh ``` ``` -------------------------------- ### Install InspireFace Python Package Manually Source: https://github.com/hyperinspire/inspireface/blob/master/python/README.md Install the InspireFace Python package after copying the dynamic library. ```bash python setup.py install ``` -------------------------------- ### TensorRT Compilation Setup Source: https://github.com/hyperinspire/inspireface/blob/master/README.md Configure environment variables for TensorRT-accelerated compilation on Linux. Ensure CUDA, cuDNN, and TensorRT-10 are installed and their paths are correctly set. ```bash # Example, Change to your TensorRT-10 path export TENSORRT_ROOT=/user/tunm/software/TensorRT-10 ``` -------------------------------- ### Multi-platform Compilation with Docker Source: https://github.com/hyperinspire/inspireface/blob/master/README.md Use these Docker Compose commands to build InspireFace for various platforms and configurations. Ensure Docker is installed beforehand. ```bash # Build x86 Ubuntu18.04 docker-compose up build-ubuntu18 ``` ```bash # Build armv7 cross-compile docker-compose up build-cross-armv7-armhf ``` ```bash # Build armv7 with support RV1109RV1126 device NPU cross-complie docker-compose up build-cross-rv1109rv1126-armhf ``` ```bash # Build armv7 with support RV1106 device NPU cross-complie docker-compose up build-cross-rv1106-armhf-uclibc ``` ```bash # Build armv8 with support RK356x device NPU cross-complie docker-compose up build-cross-rk356x-aarch64 ``` ```bash # Build Android with support arm64-v8a and armeabi-v7a docker-compose up build-cross-android ``` ```bash # Compile the tensorRT back-end based on CUDA12 and then Ubuntu22.04 docker-compose up build-tensorrt-cuda12-ubuntu22 ``` ```bash # Build all docker-compose up ``` -------------------------------- ### Python Native Face Detection Example Source: https://github.com/hyperinspire/inspireface/blob/master/README.md Python sample for face detection using the InspireFace library. Requires OpenCV and other dependencies. Ensure the native library is correctly linked. ```python import cv2 import inspireface as isf # Step 1: Initialize the SDK globally (only needs to be called once per application) ret = isf.reload() assert ret, "Launch failure. Please ensure the resource path is correct." # Optional features, loaded during session creation based on the modules specified. opt = isf.HF_ENABLE_FACE_POSE session = isf.InspireFaceSession(opt, isf.HF_DETECT_MODE_ALWAYS_DETECT) # Load the image using OpenCV. image = cv2.imread(image_path) assert image is not None, "Please check that the image path is correct." # Perform face detection on the image. faces = session.face_detection(image) print(f"face detection: {len(faces)} found") # Copy the image for drawing the bounding boxes. draw = image.copy() for idx, face in enumerate(faces): print(f"{ '==' * 20}") print(f"idx: {idx}") # Print Euler angles of the face. print(f"roll: {face.roll}, yaw: {face.yaw}, pitch: {face.pitch}") # Draw bounding box around the detected face. x1, y1, x2, y2 = face.location cv2.rectangle(draw, (x1, y1), (x2, y2), (0, 0, 255), 2) ``` -------------------------------- ### Execute Quick Test Script (General) Source: https://github.com/hyperinspire/inspireface/blob/master/README.md Run a bash script for quick testing on various systems, including Ubuntu. This script handles downloading test files and building the test program. ```bash bash ci/quick_test_local.sh ``` -------------------------------- ### InspireFaceSession Initialization and Face Detection Source: https://context7.com/hyperinspire/inspireface/llms.txt Demonstrates how to initialize an InspireFaceSession with various optional modules, set detection parameters, and perform face detection on an image. ```APIDOC ## InspireFaceSession Initialization and Face Detection ### Description Initializes an InspireFaceSession with specified optional modules and detection modes. It then performs face detection on a given image and prints the number of detected faces along with their bounding boxes and confidence scores. ### Method `InspireFaceSession(opt, detect_mode, max_detect_num)` `session.set_detection_confidence_threshold(threshold)` `session.set_filter_minimum_face_pixel_size(size)` `session.face_detection(image)` ### Parameters - **opt** (int): Bitmask of optional modules to enable (e.g., `isf.HF_ENABLE_FACE_RECOGNITION`, `isf.HF_ENABLE_QUALITY`). - **detect_mode** (int): The detection mode (e.g., `isf.HF_DETECT_MODE_ALWAYS_DETECT`). - **max_detect_num** (int, optional): Maximum number of faces to detect. Defaults to system default. - **threshold** (float): Minimum confidence threshold for face detection. - **size** (int): Minimum pixel size for a face to be considered. - **image** (numpy.ndarray): The input image for face detection. ### Request Example ```python import cv2 import inspireface as isf opt = ( isf.HF_ENABLE_FACE_RECOGNITION | isf.HF_ENABLE_QUALITY | isf.HF_ENABLE_MASK_DETECT | isf.HF_ENABLE_LIVENESS | isf.HF_ENABLE_FACE_ATTRIBUTE | isf.HF_ENABLE_FACE_EMOTION ) session = isf.InspireFaceSession(opt, isf.HF_DETECT_MODE_ALWAYS_DETECT, max_detect_num=10) session.set_detection_confidence_threshold(0.5) session.set_filter_minimum_face_pixel_size(32) image = cv2.imread("group.jpg") assert image is not None faces = session.face_detection(image) print(f"Detected {len(faces)} face(s)") for face in faces: x1, y1, x2, y2 = face.location print(f" ID={face.track_id} box=({x1},{y1})→({x2},{y2})" f" conf={face.detection_confidence:.3f}" f" roll={face.roll:.1f}° yaw={face.yaw:.1f}° pitch={face.pitch:.1f}°") lmk = session.get_face_dense_landmark(face) kp5 = session.get_face_five_key_points(face) print(f" landmarks={lmk.shape} keypoints={kp5.shape}") ``` ### Response #### Success Response Prints detected face information including ID, bounding box, confidence, rotation angles, and landmark shapes. #### Response Example ``` Detected 2 face(s) ID=1 box=(142,87)→(340,332) conf=0.982 roll=2.1° yaw=-5.3° pitch=1.8° landmarks=(106, 2) keypoints=(5, 2) ``` ``` -------------------------------- ### Compile CPU Watching Sample Source: https://github.com/hyperinspire/inspireface/blob/master/cpp/sample/CMakeLists.txt Compiles the 'CPUWatchingSample' executable from 'api/sample_cpu_watching.c', linking it with the InspireFace library and extensions. ```cmake add_executable(CPUWatchingSample api/sample_cpu_watching.c) target_link_libraries(CPUWatchingSample InspireFace ${ext}) set_target_properties(CPUWatchingSample PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/sample/api/" ) ``` -------------------------------- ### Initialize InspireFace Session in Python Source: https://github.com/hyperinspire/inspireface/blob/master/README.md Create an InspireFace session with optional features and detection mode. Load images using OpenCV. ```python import cv2 import inspireface as isf # Create a session with optional features opt = isf.HF_ENABLE_NONE session = isf.InspireFaceSession(opt, isf.HF_DETECT_MODE_ALWAYS_DETECT) # Load the image using OpenCV. image = cv2.imread(image_path) ``` -------------------------------- ### Execute Quick Test Script (Linux) Source: https://github.com/hyperinspire/inspireface/blob/master/README.md Run a bash script on Ubuntu to automatically download test files and build the test program for a quick test. ```bash bash ci/quick_test_linux_x86_usual.sh ``` -------------------------------- ### Android/Java API Usage Source: https://github.com/hyperinspire/inspireface/blob/master/README.md Example of how to use the InspireFace Java API in an Android application for face detection and analysis. ```APIDOC ## Launch InspireFace Initialize the SDK. Call this only once. ```java boolean launchStatus = InspireFace.GlobalLaunch(this, InspireFace.PIKACHU); if (!launchStatus) { Log.e(TAG, "Failed to launch InspireFace"); } ``` ## Create ImageStream Create an `ImageStream` from a Bitmap. ```java ImageStream stream = InspireFace.CreateImageStreamFromBitmap(img, InspireFace.CAMERA_ROTATION_0); ``` ## Create Session Create a session with custom parameters for face detection and analysis. ```java CustomParameter parameter = InspireFace.CreateCustomParameter() .enableRecognition(true) .enableFaceQuality(true) .enableFaceAttribute(true) .enableInteractionLiveness(true) .enableLiveness(true) .enableMaskDetect(true); Session session = InspireFace.CreateSession(parameter, InspireFace.DETECT_MODE_ALWAYS_DETECT, 10, -1, -1); ``` ## Execute Face Detection Perform face detection on the `ImageStream`. ```java MultipleFaceData multipleFaceData = InspireFace.ExecuteFaceTrack(session, stream); if (multipleFaceData.detectedNum > 0) { // Get face feature FaceFeature feature = InspireFace.ExtractFaceFeature(session, stream, multipleFaceData.tokens[0]); // .... } ``` ## Release Resources Release the session and image stream resources when done. ```java InspireFace.ReleaseSession(session); InspireFace.ReleaseImageStream(stream); // Global release InspireFace.GlobalRelease(); ``` ``` -------------------------------- ### Pull Latest Models Source: https://github.com/hyperinspire/inspireface/blob/master/README.md Use this snippet to pull the latest model files for specified models. Ensure you have the inspireface library installed. ```python import inspireface for model in ["Pikachu", "Megatron"]: inspireface.pull_latest_model(model) ``` -------------------------------- ### Compile Create Session Sample Source: https://github.com/hyperinspire/inspireface/blob/master/cpp/sample/CMakeLists.txt Compiles the 'CreateSessionSample' executable from 'api/sample_create_session.c', linking it with the InspireFace library and extensions. ```cmake add_executable(CreateSessionSample api/sample_create_session.c) target_link_libraries(CreateSessionSample InspireFace ${ext}) set_target_properties(CreateSessionSample PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/sample/api/" ) ``` -------------------------------- ### Python SDK Resource Statistics and Logging Control Source: https://context7.com/hyperinspire/inspireface/llms.txt Demonstrates launching with a model pack, creating multiple sessions, showing resource statistics, releasing sessions, and disabling SDK logging. ```python import inspireface as isf isf.launch("Pikachu") sessions = [isf.InspireFaceSession(isf.HF_ENABLE_NONE, isf.HF_DETECT_MODE_ALWAYS_DETECT) for _ in range(5)] isf.show_system_resource_statistics() # shows 5 unreleased sessions for s in sessions: s.release() isf.show_system_resource_statistics() # shows 0 unreleased sessions isf.disable_logging() # suppress all SDK log output ``` -------------------------------- ### Compile Search Face Sample Source: https://github.com/hyperinspire/inspireface/blob/master/cpp/sample/CMakeLists.txt Compiles the 'SearchFaceSample' executable from 'api/sample_search_face.cpp', linking it with the InspireFace library and extensions. ```cmake add_executable(SearchFaceSample api/sample_search_face.cpp) target_link_libraries(SearchFaceSample InspireFace ${ext}) set_target_properties(SearchFaceSample PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/sample/api/" ) ``` -------------------------------- ### Initialize InspireFace Session Source: https://context7.com/hyperinspire/inspireface/llms.txt Launches the SDK with a specified model pack and creates a session with desired detection modes. TensorRT pack is for NVIDIA GPU. ```python isf.launch("Megatron_TRT") # TensorRT pack for NVIDIA GPU session = isf.InspireFaceSession(isf.HF_ENABLE_FACE_RECOGNITION, isf.HF_DETECT_MODE_ALWAYS_DETECT) ``` -------------------------------- ### Resource Monitoring and Debugging Utilities (C API) Source: https://context7.com/hyperinspire/inspireface/llms.txt Provides C API functions to monitor resource usage, get unreleased session counts, and save/display image streams for debugging. ```c #include // Print resource statistics to stdout HFDeBugShowResourceStatistics(); // Expected output example: // Sessions created=3 released=2 unreleased=1 // Streams created=5 released=5 unreleased=0 // Get unreleased session count HInt32 unreleased = 0; HFDeBugGetUnreleasedSessionsCount(&unreleased); // Save current image stream to disk for debugging codec issues HFDeBugImageStreamDecodeSave(stream, "debug_frame.jpg"); // Display image stream in a window (requires OpenCV GUI build) HFDeBugImageStreamImShow(stream); ``` -------------------------------- ### Compile Gray Input Sample Source: https://github.com/hyperinspire/inspireface/blob/master/cpp/sample/CMakeLists.txt Compiles the 'GrayInput' executable from 'api/sample_gray_input.c', linking it with the InspireFace library and extensions. ```cmake add_executable(GrayInput api/sample_gray_input.c) target_link_libraries(GrayInput InspireFace ${ext}) set_target_properties(GrayInput PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/sample/api/" ) ``` -------------------------------- ### Extract Face Features and Compare Source: https://context7.com/hyperinspire/inspireface/llms.txt Extracts a 512-dimensional feature vector from a detected face for recognition and compares two feature vectors using cosine similarity. Includes functions to get recommended thresholds and convert scores to percentages. ```python import cv2 import inspireface as isf isf.launch("Megatron") session = isf.InspireFaceSession(isf.HF_ENABLE_FACE_RECOGNITION, isf.HF_DETECT_MODE_ALWAYS_DETECT) def extract(image_path: str): img = cv2.imread(image_path) faces = session.face_detection(img) assert faces, f"No face found in {image_path}" return session.face_feature_extract(img, faces[0]) # numpy float32 array feat_a = extract("person_a_1.jpg") feat_b = extract("person_a_2.jpg") # same person, different photo feat_c = extract("person_b.jpg") # different person sim_same = isf.feature_comparison(feat_a, feat_b) sim_diff = isf.feature_comparison(feat_a, feat_c) threshold = isf.get_recommended_cosine_threshold() print(f"Recommended threshold: {threshold:.3f}") print(f"Same person similarity: {sim_same:.4f} → {'MATCH' if sim_same > threshold else 'NO MATCH'}") print(f"Diff person similarity: {sim_diff:.4f} → {'MATCH' if sim_diff > threshold else 'NO MATCH'}") # Convert cosine score to percentage pct = isf.cosine_similarity_convert_to_percentage(sim_same) print(f"Percentage match: {pct*100:.1f}%") print(f"Feature vector length: {feat_a.shape[0]}") # 512 ``` -------------------------------- ### C API Hardware Backend Configuration Source: https://context7.com/hyperinspire/inspireface/llms.txt Sets up the inference backend using C API equivalents for CUDA, CoreML (ANE), and Rockchip RGA. ```c // C API equivalent for CUDA HFSetCudaDeviceId(0); HFPrintCudaDeviceInfo(); // C API equivalent for CoreML HFSetAppleCoreMLInferenceMode(HF_APPLE_COREML_INFERENCE_MODE_ANE); // C API equivalent for Rockchip RGA HFSwitchImageProcessingBackend(HF_IMAGE_PROCESSING_RGA); // Then create session... ``` -------------------------------- ### Compile Face CRUD Sample Source: https://github.com/hyperinspire/inspireface/blob/master/cpp/sample/CMakeLists.txt Compiles the 'FaceCrudSample' executable from 'api/sample_face_crud.c', linking it with the InspireFace library and extensions. ```cmake add_executable(FaceCrudSample api/sample_face_crud.c) target_link_libraries(FaceCrudSample InspireFace ${ext}) set_target_properties(FaceCrudSample PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/sample/api/" ) ``` -------------------------------- ### Initialize Session and Detect Faces Source: https://context7.com/hyperinspire/inspireface/llms.txt Initializes an InspireFace session with multiple optional modules enabled and performs face detection on an image. Sets detection confidence and minimum face pixel size. ```python opt = (isf.HF_ENABLE_FACE_RECOGNITION | isf.HF_ENABLE_QUALITY | isf.HF_ENABLE_MASK_DETECT | isf.HF_ENABLE_LIVENESS | isf.HF_ENABLE_FACE_ATTRIBUTE | isf.HF_ENABLE_FACE_EMOTION) session = isf.InspireFaceSession(opt, isf.HF_DETECT_MODE_ALWAYS_DETECT, max_detect_num=10) session.set_detection_confidence_threshold(0.5) session.set_filter_minimum_face_pixel_size(32) image = cv2.imread("group.jpg") assert image is not None faces = session.face_detection(image) print(f"Detected {len(faces)} face(s)") for face in faces: x1, y1, x2, y2 = face.location print(f" ID={face.track_id} box=({x1},{y1})→({x2},{y2})" f ``` -------------------------------- ### Create InspireFace Session with Optional Parameters Source: https://context7.com/hyperinspire/inspireface/llms.txt Create a session by OR-ing feature flags. Multiple independent sessions can exist concurrently for multi-threaded use. HF_DETECT_MODE_ALWAYS_DETECT suits single images; HF_DETECT_MODE_LIGHT_TRACK suits video streams. Tune detection parameters after creation. ```c #include // Combine desired feature flags HOption option = HF_ENABLE_FACE_RECOGNITION | HF_ENABLE_QUALITY | HF_ENABLE_MASK_DETECT | HF_ENABLE_LIVENESS | HF_ENABLE_FACE_ATTRIBUTE | HF_ENABLE_FACE_EMOTION; HFSession session = NULL; HResult ret = HFCreateInspireFaceSessionOptional( option, HF_DETECT_MODE_ALWAYS_DETECT, // use HF_DETECT_MODE_LIGHT_TRACK for video 20, // max faces to detect 320, // detector input pixel level (160/320/640) -1, // trackByDetectModeFPS (-1 = 30fps default) &session ); if (ret != HSUCCEED) { HFLogPrint(HF_LOG_ERROR, "Session creation failed: %ld", ret); return (int)ret; } // Tune detection parameters HFSessionSetTrackPreviewSize(session, 320); HFSessionSetFilterMinimumFacePixelSize(session, 8); HFSessionSetFaceDetectThreshold(session, 0.5f); /* ... use session ... */ // Release when done HFReleaseInspireFaceSession(session); ``` -------------------------------- ### Compile Face Comparison Sample Source: https://github.com/hyperinspire/inspireface/blob/master/cpp/sample/CMakeLists.txt Compiles the 'FaceComparisonSample' executable from 'api/sample_face_comparison.c', linking it with the InspireFace library and extensions. ```cmake add_executable(FaceComparisonSample api/sample_face_comparison.c) target_link_libraries(FaceComparisonSample InspireFace ${ext}) set_target_properties(FaceComparisonSample PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/sample/api/" ) ``` -------------------------------- ### Compile Face Tracking Benchmark Sample Source: https://github.com/hyperinspire/inspireface/blob/master/cpp/sample/CMakeLists.txt Compiles the 'FaceTrackBenchmarkSample' executable from 'api/sample_face_track_benchmark.c', linking it with the InspireFace library and extensions. ```cmake add_executable(FaceTrackBenchmarkSample api/sample_face_track_benchmark.c) target_link_libraries(FaceTrackBenchmarkSample InspireFace ${ext}) set_target_properties(FaceTrackBenchmarkSample PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/sample/api/" ) ``` -------------------------------- ### Compile Face Feature Hub Sample Source: https://github.com/hyperinspire/inspireface/blob/master/cpp/sample/CMakeLists.txt Compiles the 'FaceFeatureHubSample' executable from 'api/sample_feature_hub.c', linking it with the InspireFace library and extensions. ```cmake add_executable(FaceFeatureHubSample api/sample_feature_hub.c) target_link_libraries(FaceFeatureHubSample InspireFace ${ext}) set_target_properties(FaceFeatureHubSample PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/sample/api/" ) ``` -------------------------------- ### Compile Face Tracking Sample Source: https://github.com/hyperinspire/inspireface/blob/master/cpp/sample/CMakeLists.txt Compiles the 'FaceTrackSample' executable from 'api/sample_face_track.c', linking it with the InspireFace library and extensions. ```cmake add_executable(FaceTrackSample api/sample_face_track.c) target_link_libraries(FaceTrackSample InspireFace ${ext}) set_target_properties(FaceTrackSample PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/sample/api/" ) ``` -------------------------------- ### Configure Hardware Acceleration Backends Source: https://context7.com/hyperinspire/inspireface/llms.txt Sets the inference backend for hardware acceleration before session creation. Supports Apple CoreML/ANE, NVIDIA CUDA, and Rockchip RGA. ```python import inspireface as isf # --- Apple CoreML / ANE (macOS, iOS) --- # Must be called before creating a session isf.switch_apple_coreml_inference_mode(isf.HF_APPLE_COREML_INFERENCE_MODE_ANE) # ANE first # isf.switch_apple_coreml_inference_mode(isf.HF_APPLE_COREML_INFERENCE_MODE_GPU) # GPU first # --- NVIDIA CUDA --- if isf.check_cuda_device_support(): print(f"CUDA devices: {isf.get_num_cuda_devices()}") isf.set_cuda_device_id(0) # select GPU index isf.print_cuda_device_info() # --- Rockchip RGA (hardware image acceleration) --- isf.switch_image_processing_backend(isf.HF_IMAGE_PROCESSING_RGA) # default: CPU # isf.set_expansive_hardware_rockchip_dma_heap_path("/dev/dma_heap/system") ``` -------------------------------- ### Initialize InspireFace Session and Detect Faces Source: https://context7.com/hyperinspire/inspireface/llms.txt Initializes an InspireFace session with specified feature flags and performs face detection on a NumPy BGR image or an ImageStream. Returns a list of FaceInformation objects. ```python import cv2 import inspireface as isf isf.launch("Pikachu") ``` -------------------------------- ### Initialize and Terminate InspireFace SDK Source: https://context7.com/hyperinspire/inspireface/llms.txt Load the model pack globally before any other API call. Call HFTerminateInspireFace at program exit to free all resources. Set log level before launching. ```c #include #include int main(void) { // Set log level before launching HFSetLogLevel(HF_LOG_INFO); // Launch with path to an extracted model pack directory HResult ret = HFLaunchInspireFace("models/Pikachu"); if (ret != HSUCCEED) { HFLogPrint(HF_LOG_FATAL, "SDK launch failed: %ld", ret); return (int)ret; } // Query version HFInspireFaceVersion ver; HFQueryInspireFaceVersion(&ver); HFLogPrint(HF_LOG_INFO, "InspireFace v%d.%d.%d", ver.major, ver.minor, ver.patch); // Query launch status (1 = launched) HInt32 status = 0; HFQueryInspireFaceLaunchStatus(&status); HFLogPrint(HF_LOG_INFO, "Launch status: %d", status); /* ... run face processing ... */ HFTerminateInspireFace(); return 0; } // Expected output: // [INFO] InspireFace v1.2.3 // [INFO] Launch status: 1 ``` -------------------------------- ### Compile Face Load/Reload Sample Source: https://github.com/hyperinspire/inspireface/blob/master/cpp/sample/CMakeLists.txt Compiles the 'FaceLoadReloadSample' executable from 'api/sample_load_reload.c', linking it with the InspireFace library and extensions. ```cmake add_executable(FaceLoadReloadSample api/sample_load_reload.c) target_link_libraries(FaceLoadReloadSample InspireFace ${ext}) set_target_properties(FaceLoadReloadSample PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/sample/api/" ) ``` -------------------------------- ### Image Loading and Stream Creation Source: https://context7.com/hyperinspire/inspireface/llms.txt Demonstrates how to load an image from a file path into an HFImageBitmap and then convert it into an HFImageStream for processing. It also shows how to release the allocated resources. ```APIDOC ## HFCreateImageBitmapFromFilePath / HFCreateImageStreamFromImageBitmap ### Description Loads a decoded image into memory (`HFImageBitmap`) and converts it into a stream (`HFImageStream`) suitable for the detection pipeline. Optional rotation can be applied during stream creation. Both handles must be released after use. ### Function Signatures - `HFCreateImageBitmapFromFilePath(const char* filePath, int channels, HFImageBitmap* outBitmap) - `HFCreateImageStreamFromImageBitmap(HFImageBitmap bitmap, HFRotation rotation, HFImageStream* outStream) ### Parameters #### HFCreateImageBitmapFromFilePath - **filePath** (const char*) - Path to the image file. - **channels** (int) - Number of color channels (e.g., 3 for BGR). - **outBitmap** (HFImageBitmap*) - Pointer to store the created image bitmap handle. #### HFCreateImageStreamFromImageBitmap - **bitmap** (HFImageBitmap) - The image bitmap to wrap. - **rotation** (HFRotation) - Optional rotation to apply (e.g., `HF_CAMERA_ROTATION_0`). - **outStream** (HFImageStream*) - Pointer to store the created image stream handle. ### Resource Management - `HFReleaseImageBitmap(HFImageBitmap bitmap)` - `HFReleaseImageStream(HFImageStream stream)` ### Example Usage ```c #include HFImageBitmap bitmap = NULL; HFImageStream stream = NULL; // Load BGR image from file (channels=3) HResult ret = HFCreateImageBitmapFromFilePath("photo.jpg", 3, &bitmap); if (ret != HSUCCEED) { HFLogPrint(HF_LOG_ERROR, "Failed to load image: %ld", ret); return (int)ret; } // Wrap as stream with no rotation ret = HFCreateImageStreamFromImageBitmap(bitmap, HF_CAMERA_ROTATION_0, &stream); if (ret != HSUCCEED) { HFLogPrint(HF_LOG_ERROR, "Failed to create stream: %ld", ret); HFReleaseImageBitmap(bitmap); return (int)ret; } /* ... use stream ... */ HFReleaseImageStream(stream); HFReleaseImageBitmap(bitmap); ``` ``` -------------------------------- ### Configure RV1106 Device Samples Source: https://github.com/hyperinspire/inspireface/blob/master/cpp/sample/CMakeLists.txt Adds executables for face detection, face attribute, and image processing samples specifically for the RV1106 device type. It links against the InspireFace library and sets the runtime output directory. ```cmake if(ISF_RK_DEVICE_TYPE STREQUAL "RV1106") add_executable(FaceTrackSampleRV1106 rv1106/face_detect.cpp) target_link_libraries(FaceTrackSampleRV1106 InspireFace ${ext}) set_target_properties(FaceTrackSampleRV1106 PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/sample/internal/" ) add_executable(FaceAttributeSampleRV1106 rv1106/face_attribute.cpp) target_link_libraries(FaceAttributeSampleRV1106 InspireFace ${ext}) set_target_properties(FaceAttributeSampleRV1106 PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/sample/internal/" ) add_executable(NexusImageSample rv1106/rga_image.cpp) target_link_libraries(NexusImageSample InspireFace ${ext}) set_target_properties(NexusImageSample PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/sample/internal/" ) ``` -------------------------------- ### InspireFace Android/Java API Usage Source: https://github.com/hyperinspire/inspireface/blob/master/README.md Demonstrates the core Java API calls for launching, creating streams and sessions, executing face detection, and releasing resources. Ensure GlobalLaunch is called only once. ```java // Launch InspireFace, only need to call once boolean launchStatus = InspireFace.GlobalLaunch(this, InspireFace.PIKACHU); if (!launchStatus) { Log.e(TAG, "Failed to launch InspireFace"); } // Create a ImageStream ImageStream stream = InspireFace.CreateImageStreamFromBitmap(img, InspireFace.CAMERA_ROTATION_0); // Create a session CustomParameter parameter = InspireFace.CreateCustomParameter() .enableRecognition(true) .enableFaceQuality(true) .enableFaceAttribute(true) .enableInteractionLiveness(true) .enableLiveness(true) .enableMaskDetect(true); Session session = InspireFace.CreateSession(parameter, InspireFace.DETECT_MODE_ALWAYS_DETECT, 10, -1, -1); // Execute face detection MultipleFaceData multipleFaceData = InspireFace.ExecuteFaceTrack(session, stream); if (multipleFaceData.detectedNum > 0) { // Get face feature FaceFeature feature = InspireFace.ExtractFaceFeature(session, stream, multipleFaceData.tokens[0]); // .... } // .... // Release resource InspireFace.ReleaseSession(session); InspireFace.ReleaseImageStream(stream); // Global release InspireFace.GlobalRelease(); ``` -------------------------------- ### Compile C++ Multithreading Sample Source: https://github.com/hyperinspire/inspireface/blob/master/cpp/sample/CMakeLists.txt Compiles the 'CppMultithreadingSample' executable from 'api/sample_cpp_multithreading.cpp', linking it with the InspireFace library and extensions. ```cmake add_executable(CppMultithreadingSample api/sample_cpp_multithreading.cpp) target_link_libraries(CppMultithreadingSample InspireFace ${ext}) set_target_properties(CppMultithreadingSample PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/sample/api/" ) ``` -------------------------------- ### Configure Build Options for Sample Programs Source: https://github.com/hyperinspire/inspireface/blob/master/cpp/sample/CMakeLists.txt Defines boolean options to control the compilation of cluttered and internal sample programs, useful for debugging during development. ```cmake option(ISF_BUILD_SAMPLE_CLUTTERED "Whether to compile the cluttered sample program (debug code during development)" OFF) option(ISF_BUILD_SAMPLE_INTERNAL "Whether to compile the internal sample program (debug code during development)" OFF) ``` -------------------------------- ### Run Unit Tests for InspireFace Source: https://github.com/hyperinspire/inspireface/blob/master/python/README.md Execute the project's unit tests using the unittest module. Test content can be adjusted in `test/test_settings.py`. ```bash python -m unittest discover -s test ``` -------------------------------- ### Hardware Acceleration Configuration Source: https://context7.com/hyperinspire/inspireface/llms.txt This section explains how to configure hardware acceleration for inference backends before creating any session. It covers support for Apple ANE/CoreML, NVIDIA CUDA, and Rockchip RGA. ```APIDOC ## Hardware Acceleration Configuration Configure the inference backend before creating any session. Supports Apple ANE/CoreML on macOS/iOS, CUDA/TensorRT on NVIDIA GPUs, and Rockchip RGA hardware image acceleration. ### Apple CoreML / ANE (macOS, iOS) ```python import inspireface as isf # Must be called before creating a session isf.switch_apple_coreml_inference_mode(isf.HF_APPLE_COREML_INFERENCE_MODE_ANE) # ANE first # isf.switch_apple_coreml_inference_mode(isf.HF_APPLE_COREML_INFERENCE_MODE_GPU) # GPU first ``` ### NVIDIA CUDA ```python import inspireface as isf if isf.check_cuda_device_support(): print(f"CUDA devices: {isf.get_num_cuda_devices()}") isf.set_cuda_device_id(0) # select GPU index isf.print_cuda_device_info() ``` ### Rockchip RGA (hardware image acceleration) ```python import inspireface as isf isf.switch_image_processing_backend(isf.HF_IMAGE_PROCESSING_RGA) # default: CPU # isf.set_expansive_hardware_rockchip_dma_heap_path("/dev/dma_heap/system") ``` ``` -------------------------------- ### Compile Feature Hub Persistence Sample Source: https://github.com/hyperinspire/inspireface/blob/master/cpp/sample/CMakeLists.txt Compiles the 'FeatureHubPersistenceSample' executable from 'api/sample_feature_hub_persistence.c', linking it with the InspireFace library and extensions. ```cmake add_executable(FeatureHubPersistenceSample api/sample_feature_hub_persistence.c) target_link_libraries(FeatureHubPersistenceSample InspireFace ${ext}) set_target_properties(FeatureHubPersistenceSample PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/sample/api/" ) ``` -------------------------------- ### Compile C++ Resource Pool Sample Source: https://github.com/hyperinspire/inspireface/blob/master/cpp/sample/CMakeLists.txt Compiles the 'CppResourcePoolSample' executable from 'api/sample_cpp_resource_pool.cpp', linking it with the InspireFace library and extensions. ```cmake add_executable(CppResourcePoolSample api/sample_cpp_resource_pool.cpp) target_link_libraries(CppResourcePoolSample InspireFace ${ext}) set_target_properties(CppResourcePoolSample PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/sample/api/" ) ``` -------------------------------- ### C++ Test Resource Directory Structure Source: https://github.com/hyperinspire/inspireface/blob/master/README.md Shows the directory structure for test resources, including model packages. ```bash test_res ├── data ├── images ├── pack <-- The model package files are here ├── save ├── valid_lfw_funneled.txt ├── video └── video_frames ``` -------------------------------- ### Configure RKNN API Library for rknpu1 Source: https://github.com/hyperinspire/inspireface/blob/master/cpp/sample/CMakeLists.txt Sets up the library path for the RKNN API when targeting rknpu1, enabling dynamic linking. ```cmake if (ISF_ENABLE_RKNN AND ISF_RKNPU_MAJOR STREQUAL "rknpu1") set(ISF_RKNN_API_LIB ${ISF_THIRD_PARTY_DIR}/inspireface-precompile-lite/rknn/${ISF_RKNPU_MAJOR}/runtime/${ISF_RK_DEVICE_TYPE}/Linux/librknn_api/${CPU_ARCH}/) link_directories(${ISF_RKNN_API_LIB}) set(ext rknn_api dl) endif () ``` -------------------------------- ### Load Image from File and Create Stream Source: https://context7.com/hyperinspire/inspireface/llms.txt Loads a BGR image from a file path into an HFImageBitmap and then converts it into an HFImageStream for processing. Ensure to release both handles after use. An alternative for creating a stream directly from a raw buffer is commented out. ```c #include HFImageBitmap bitmap = NULL; HFImageStream stream = NULL; // Load BGR image from file (channels=3) HResult ret = HFCreateImageBitmapFromFilePath("photo.jpg", 3, &bitmap); if (ret != HSUCCEED) { HFLogPrint(HF_LOG_ERROR, "Failed to load image: %ld", ret); return (int)ret; } // Wrap as stream with no rotation ret = HFCreateImageStreamFromImageBitmap(bitmap, HF_CAMERA_ROTATION_0, &stream); if (ret != HSUCCEED) { HFLogPrint(HF_LOG_ERROR, "Failed to create stream: %ld", ret); HFReleaseImageBitmap(bitmap); return (int)ret; } // --- OR --- create a stream directly from a raw buffer (e.g., from camera callback) // uint8_t* raw_bgr = camera_get_frame(); // HFImageData img_data = { raw_bgr, width, height, HF_STREAM_BGR, HF_CAMERA_ROTATION_0 }; // HFCreateImageStream(&img_data, &stream); /* ... run face track ... */ HFReleaseImageStream(stream); HFReleaseImageBitmap(bitmap); ```