From f2db04e640ab1ae8d72197ceadc93def46cdba0b Mon Sep 17 00:00:00 2001 From: trung09122002 Date: Wed, 13 May 2026 17:31:00 +0700 Subject: [PATCH] Add quartz inspection core ignore rules --- .gitignore | 67 ++++ AGENTS.md | 30 ++ CMakeLists.txt | 137 ++++++++ PROJECT_CONTEXT.md | 68 ++++ README.md | 94 +++++ config/labels.names | 6 + scripts/build_engine.sh | 31 ++ scripts/export_yolo26_seg_onnx.py | 59 ++++ src/hik_predict_trt.cpp | 549 ++++++++++++++++++++++++++++++ 9 files changed, 1041 insertions(+) create mode 100644 .gitignore create mode 100644 AGENTS.md create mode 100644 CMakeLists.txt create mode 100644 PROJECT_CONTEXT.md create mode 100644 README.md create mode 100644 config/labels.names create mode 100755 scripts/build_engine.sh create mode 100755 scripts/export_yolo26_seg_onnx.py create mode 100644 src/hik_predict_trt.cpp diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fff9750 --- /dev/null +++ b/.gitignore @@ -0,0 +1,67 @@ +# Build outputs +build/ +build_*/ +cmake-build-*/ +CMakeFiles/ +CMakeCache.txt +cmake_install.cmake +Makefile +*.o +*.a +*.so +*.so.* +*.dll +*.dylib +*.exe + +# Runtime captures and generated outputs +captures/ +outputs/ +logs/ +*.log + +# Model artifacts and training/export outputs +models/ +runs/ +*.pt +*.pth +*.onnx +*.engine +*.trt +*.plan +*.wts + +# Vendored/external repositories +third_party/ +agent_skills_codex/ + +# Python caches and virtual environments +__pycache__/ +*.py[cod] +*.pyo +.pytest_cache/ +.mypy_cache/ +.ruff_cache/ +.venv/ +venv/ +env/ + +# IDE/editor files +.vscode/ +.idea/ +*.swp +*.swo +*~ + + +# OS files +.DS_Store +Thumbs.db + +# Local environment files +.env +.env.* +*.local + +# Local Codex/agent workspace +.agents/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..c6a5ab4 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,30 @@ +# Robotics / CV / ROS Repository Guidance + +This repository may contain robotics, ROS, ROS 2, computer vision, edge AI, embedded, simulation, or deployment code. Treat every project-specific detail as unknown until verified from this repository or from user-provided context. + +## Project Context + +- Read `PROJECT_CONTEXT.md` if present before making assumptions. +- Prefer verified repository facts over generic robotics assumptions. +- If `ROS_TOPIC_MAP.md`, `TF_FRAME_MAP.md`, or `MODEL_DEPLOYMENT_CONTEXT.md` exists, read the relevant file before analyzing related behavior. +- If a context file is missing or incomplete, use `Unknown / needs confirmation` for unverified facts. + +## Discovery Rules + +- Discover package names, node names, launch files, parameters, topics, services, actions, TF frames, model paths, robot names, hardware, and build/test commands from the target repo at usage time. +- Do not invent commands, topics, frames, model paths, hardware, calibration files, accelerators, middleware, operating systems, or deployment targets. +- Generic examples are allowed only when clearly marked as examples. +- Consider both ROS 1 and ROS 2 conventions where relevant. + +## Robotics Engineering Checks + +- Check message contracts, timestamps, coordinate frames, units, calibration, synchronization, QoS or queue settings, lifecycle behavior, launch parameters, and runtime configuration. +- Consider safety, watchdogs, failure modes, degraded sensor input, timing, resource limits, and hardware interaction boundaries. +- For CV and AI code, check image encodings, camera models, preprocessing, postprocessing, model input/output contracts, conversion precision, accelerator support, and runtime memory pressure. + +## Change Discipline + +- Keep edits scoped to the requested task. +- Do not rewrite unrelated launch, configuration, model, or hardware files. +- Preserve user changes and repository conventions. +- At the end, summarize changed files and verification performed. diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..db94543 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,137 @@ +cmake_minimum_required(VERSION 3.16) +project(quartz_inspection_core LANGUAGES CXX CUDA) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) +set(CMAKE_CUDA_STANDARD 14) +set(CMAKE_CUDA_STANDARD_REQUIRED ON) + +option(ENABLE_WARNINGS "Enable compiler warnings" ON) + +set(YOLOS_TRT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/third_party/YOLOs-CPP-TensorRT" + CACHE PATH "Path to Geekgineer YOLOs-CPP-TensorRT checkout") +set(MVS_DIR "/opt/MVS" CACHE PATH "Path to Hikvision MVS SDK") + +if(NOT EXISTS "${YOLOS_TRT_DIR}/include/yolos/tasks/segmentation.hpp") + message(FATAL_ERROR + "YOLOs-CPP-TensorRT was not found at ${YOLOS_TRT_DIR}.\n" + "Clone it with:\n" + " git clone --depth 1 https://github.com/Geekgineer/YOLOs-CPP-TensorRT.git ${YOLOS_TRT_DIR}" + ) +endif() + +find_package(OpenCV REQUIRED) +find_package(Threads REQUIRED) + +find_package(CUDAToolkit QUIET) +if(CUDAToolkit_FOUND) + set(CUDA_RUNTIME_LIB CUDA::cudart) + set(CUDA_VERSION_TEXT "${CUDAToolkit_VERSION}") +else() + find_package(CUDA REQUIRED) + set(CUDA_RUNTIME_LIB "${CUDA_CUDART_LIBRARY}") + set(CUDA_VERSION_TEXT "${CUDA_VERSION}") +endif() + +if(NOT DEFINED CMAKE_CUDA_ARCHITECTURES) + set(CMAKE_CUDA_ARCHITECTURES "75;80;86;89;90") +endif() + +if(NOT DEFINED TENSORRT_DIR) + set(TENSORRT_SEARCH_PATHS + "$ENV{TENSORRT_DIR}" + "/usr/lib/x86_64-linux-gnu" + "/usr/local/tensorrt" + "/usr" + ) + foreach(path ${TENSORRT_SEARCH_PATHS}) + if(EXISTS "${path}/libnvinfer.so" OR EXISTS "${path}/lib/libnvinfer.so" OR EXISTS "${path}/lib64/libnvinfer.so") + set(TENSORRT_DIR "${path}") + break() + endif() + endforeach() +endif() + +find_path(TENSORRT_INCLUDE_DIR NvInfer.h + HINTS ${TENSORRT_DIR}/include /usr/include/x86_64-linux-gnu /usr/include +) +find_library(NVINFER_LIB nvinfer + HINTS ${TENSORRT_DIR}/lib ${TENSORRT_DIR}/lib64 ${TENSORRT_DIR} /usr/lib/x86_64-linux-gnu +) +find_library(NVONNXPARSER_LIB nvonnxparser + HINTS ${TENSORRT_DIR}/lib ${TENSORRT_DIR}/lib64 ${TENSORRT_DIR} /usr/lib/x86_64-linux-gnu +) + +if(NOT TENSORRT_INCLUDE_DIR OR NOT NVINFER_LIB) + message(FATAL_ERROR + "TensorRT not found. Install TensorRT 10+ or configure with:\n" + " cmake -S . -B build -DTENSORRT_DIR=/path/to/TensorRT" + ) +endif() + +find_path(MVS_INCLUDE_DIR MvCameraControl.h + HINTS "${MVS_DIR}/include" /opt/MVS/include +) +find_library(MVS_CAMERA_LIB MvCameraControl + HINTS "${MVS_DIR}/lib/64" /opt/MVS/lib/64 +) + +if(NOT MVS_INCLUDE_DIR OR NOT MVS_CAMERA_LIB) + message(FATAL_ERROR + "Hikvision MVS SDK not found. Set -DMVS_DIR=/path/to/MVS." + ) +endif() + +if(ENABLE_WARNINGS) + add_compile_options( + $<$:-Wall> + $<$:-Wextra> + $<$:-Wpedantic> + ) +endif() + +add_library(yolos_cuda_preprocessing STATIC + "${YOLOS_TRT_DIR}/include/yolos/core/cuda_preprocessing.cu" +) +target_include_directories(yolos_cuda_preprocessing PRIVATE + "${YOLOS_TRT_DIR}/include" + "${TENSORRT_INCLUDE_DIR}" + ${CUDA_INCLUDE_DIRS} +) +target_link_libraries(yolos_cuda_preprocessing PRIVATE ${CUDA_RUNTIME_LIB}) +set_target_properties(yolos_cuda_preprocessing PROPERTIES + CUDA_SEPARABLE_COMPILATION ON + POSITION_INDEPENDENT_CODE ON +) + +add_executable(hik_predict_trt src/hik_predict_trt.cpp) +target_include_directories(hik_predict_trt PRIVATE + "${YOLOS_TRT_DIR}/include" + "${TENSORRT_INCLUDE_DIR}" + "${MVS_INCLUDE_DIR}" + ${CUDA_INCLUDE_DIRS} +) +target_link_libraries(hik_predict_trt PRIVATE + ${OpenCV_LIBS} + ${NVINFER_LIB} + ${MVS_CAMERA_LIB} + ${CUDA_RUNTIME_LIB} + yolos_cuda_preprocessing + Threads::Threads +) +if(NVONNXPARSER_LIB) + target_link_libraries(hik_predict_trt PRIVATE ${NVONNXPARSER_LIB}) +endif() + +set_target_properties(hik_predict_trt PROPERTIES + BUILD_RPATH "${MVS_DIR}/lib/64" + INSTALL_RPATH "${MVS_DIR}/lib/64" +) + +message(STATUS "OpenCV: ${OpenCV_VERSION}") +message(STATUS "CUDA: ${CUDA_VERSION_TEXT}") +message(STATUS "TensorRT include: ${TENSORRT_INCLUDE_DIR}") +message(STATUS "TensorRT lib: ${NVINFER_LIB}") +message(STATUS "MVS include: ${MVS_INCLUDE_DIR}") +message(STATUS "MVS lib: ${MVS_CAMERA_LIB}") diff --git a/PROJECT_CONTEXT.md b/PROJECT_CONTEXT.md new file mode 100644 index 0000000..3539781 --- /dev/null +++ b/PROJECT_CONTEXT.md @@ -0,0 +1,68 @@ +# Project Context + +Use this file for verified target-repository facts only. Keep unknown values as `Unknown / needs confirmation`. + +## Project Identity + +- Project name: Unknown / needs confirmation +- Robot or system: Unknown / needs confirmation +- Primary use case: Unknown / needs confirmation +- Repository role: Unknown / needs confirmation + +## Stack + +- ROS distribution: Unknown / needs confirmation +- ROS variant: Unknown / needs confirmation +- Operating system: Unknown / needs confirmation +- Build system: Unknown / needs confirmation +- Main languages: Unknown / needs confirmation +- Simulation stack: Unknown / needs confirmation + +## Repository Layout + +- ROS packages: Unknown / needs confirmation +- Launch/config locations: Unknown / needs confirmation +- Source locations: Unknown / needs confirmation +- Test locations: Unknown / needs confirmation +- Documentation locations: Unknown / needs confirmation + +## Runtime Interfaces + +- Main nodes: Unknown / needs confirmation +- Topics: Unknown / needs confirmation +- Services: Unknown / needs confirmation +- Actions: Unknown / needs confirmation +- Parameters: Unknown / needs confirmation +- TF frames: Unknown / needs confirmation + +## Sensors And Hardware + +- Cameras: Unknown / needs confirmation +- LiDAR: Unknown / needs confirmation +- IMU: Unknown / needs confirmation +- Compute target: Unknown / needs confirmation +- Accelerators: Unknown / needs confirmation +- Actuators or robot base: Unknown / needs confirmation + +## CV And AI + +- Models: Unknown / needs confirmation +- Model formats: Unknown / needs confirmation +- Inference runtimes: Unknown / needs confirmation +- Preprocessing: Unknown / needs confirmation +- Postprocessing: Unknown / needs confirmation +- Calibration files: Unknown / needs confirmation + +## Commands + +- Build command: Unknown / needs confirmation +- Test command: Unknown / needs confirmation +- Lint command: Unknown / needs confirmation +- Launch examples: Unknown / needs confirmation +- Bag playback examples: Unknown / needs confirmation + +## Verification Notes + +- Last inspected by Codex: Unknown / needs confirmation +- Verified files: Unknown / needs confirmation +- Open questions: Unknown / needs confirmation diff --git a/README.md b/README.md new file mode 100644 index 0000000..654e9f7 --- /dev/null +++ b/README.md @@ -0,0 +1,94 @@ +# Quartz Inspection Core + +C++ TensorRT realtime inspection app for the Hikvision camera pipeline.https://marketplace.cursorapi.com/open-vsx-mirror/vscode/asset/openai/chatgpt/26.5506.31421/Microsoft.VisualStudio.Services.Icons.Default?targetPlatform=linux-x64 + +This folder is intentionally separate from the Python training and prediction code. It contains its own copied `runs/` model artifacts while adding a faster runtime path based on `Geekgineer/YOLOs-CPP-TensorRT`. + +## Layout + +- `src/hik_predict_trt.cpp`: Hikvision camera + YOLO26 segmentation TensorRT runtime. +- `config/labels.names`: class names used by the C++ runtime. +- `scripts/export_yolo26_seg_onnx.py`: exports `runs/segment/yolo26_tile_seg_v3/weights/best.pt` to ONNX. +- `scripts/build_engine.sh`: builds an FP16 TensorRT engine with `trtexec`. +- `third_party/YOLOs-CPP-TensorRT`: cloned dependency. + +## Prerequisites + +- NVIDIA driver working (`nvidia-smi` must succeed). +- CUDA and TensorRT compatible with `YOLOs-CPP-TensorRT`. +- OpenCV C++ development files. +- Hikvision MVS SDK at `/opt/MVS`. + +Current machine note: CUDA 12.2, TensorRT 10.1.0, OpenCV 4.2, and Hikvision MVS SDK were detected. The FP16 TensorRT engine has been built at `models/yolo26_tile_seg_v3_fp16.trt`. + +## Build + +```bash +cd /home/quangtrung/quartz_inspection_core +python3 scripts/export_yolo26_seg_onnx.py +scripts/build_engine.sh +cmake -S . -B build \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_CUDA_COMPILER=/usr/local/cuda-12.2/bin/nvcc +cmake --build build -j +``` + +If TensorRT is installed outside common paths, point both engine generation and CMake at it: + +```bash +TENSORRT_DIR=/path/to/TensorRT scripts/build_engine.sh +cmake -S . -B build \ + -DCMAKE_BUILD_TYPE=Release \ + -DTENSORRT_DIR=/path/to/TensorRT \ + -DCMAKE_CUDA_COMPILER=/usr/local/cuda-12.2/bin/nvcc +``` + +If `trtexec` is elsewhere, use: + +```bash +TRTEXEC=/path/to/trtexec scripts/build_engine.sh +``` + +## Run + +```bash +./build/hik_predict_trt \ + --engine models/yolo26_tile_seg_v3_fp16.trt \ + --labels config/labels.names +``` + +Useful options: + +- `--pixel-format mono8|bgr8|bayer_rg8` +- `--frame-skip 1` +- `--imgsz 864` +- `--display-scale 0.3` +- `--save-dir captures` + +Keys: + +- `ESC` or `q`: exit. +- `s`: save current original/result frame. + +## Behavior Matched From `hik_predict.py` + +- Resize camera frame before inference when the max side is larger than `imgsz`. +- 4-pass fallback: + 1. original frame at `conf=0.175` + 2. light CLAHE at `conf=0.30` + 3. gamma correction for dark/bright frames at `conf=0.30` + 4. strong CLAHE at `conf=0.08`, retaining only `crack` +- Single-class filter: + - drops class `good` + - if multiple defect classes remain, keeps only the class with the highest max confidence +- Mask cleanup and overlay drawing similar to `ResultVisualizer`. + +## Class Mapping Note + +`config/labels.names` follows the current `predict.py` mapping: + +```text +crack, glue_strip, good, gray_stroke, oil, rough +``` + +`tile_yolo26/data.yaml` currently lists 5 classes. If the trained model really has 5 outputs, update `labels.names` and the class IDs in `src/hik_predict_trt.cpp` to match the exported model before production use. diff --git a/config/labels.names b/config/labels.names new file mode 100644 index 0000000..8677d28 --- /dev/null +++ b/config/labels.names @@ -0,0 +1,6 @@ +crack +glue_strip +good +gray_stroke +oil +rough diff --git a/scripts/build_engine.sh b/scripts/build_engine.sh new file mode 100755 index 0000000..a5645b9 --- /dev/null +++ b/scripts/build_engine.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CORE_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)" +ONNX_PATH="${1:-${CORE_DIR}/models/yolo26_tile_seg_v3.onnx}" +ENGINE_PATH="${2:-${CORE_DIR}/models/yolo26_tile_seg_v3_fp16.trt}" + +TRTEXEC="${TRTEXEC:-}" +if [[ -z "${TRTEXEC}" ]]; then + if command -v trtexec >/dev/null 2>&1; then + TRTEXEC="$(command -v trtexec)" + elif [[ -n "${TENSORRT_DIR:-}" && -x "${TENSORRT_DIR}/bin/trtexec" ]]; then + TRTEXEC="${TENSORRT_DIR}/bin/trtexec" + elif [[ -x "/usr/src/tensorrt/bin/trtexec" ]]; then + TRTEXEC="/usr/src/tensorrt/bin/trtexec" + else + echo "trtexec was not found. Install TensorRT 10+ or set TRTEXEC=/path/to/trtexec." >&2 + exit 1 + fi +fi + +mkdir -p "$(dirname "${ENGINE_PATH}")" +"${TRTEXEC}" \ + --onnx="${ONNX_PATH}" \ + --saveEngine="${ENGINE_PATH}" \ + --fp16 \ + --useCudaGraph \ + --noDataTransfers + +echo "TensorRT engine written to: ${ENGINE_PATH}" diff --git a/scripts/export_yolo26_seg_onnx.py b/scripts/export_yolo26_seg_onnx.py new file mode 100755 index 0000000..c2b3085 --- /dev/null +++ b/scripts/export_yolo26_seg_onnx.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +"""Export the trained YOLO26 segmentation model to ONNX for TensorRT.""" + +import os +from pathlib import Path + +from ultralytics import YOLO + + +CORE_DIR = Path(__file__).resolve().parents[1] +MODEL = Path(os.environ.get( + "YOLO26_MODEL", + CORE_DIR / "runs/segment/yolo26_tile_seg_v3/weights/best.pt", +)) +OUT_DIR = CORE_DIR / "models" +EXISTING_ONNX = CORE_DIR / "runs/segment/yolo26_tile_seg_v3/weights/best.onnx" + + +def require_yolo26_support() -> None: + from ultralytics.nn.modules import head + + if not hasattr(head, "Segment26"): + raise RuntimeError( + "This checkpoint uses the YOLO26 Segment26 head, but the active " + "ultralytics install does not provide it. Run this script with the " + "same YOLO26-capable Python environment used for training." + ) + + +def main() -> None: + OUT_DIR.mkdir(parents=True, exist_ok=True) + target = OUT_DIR / "yolo26_tile_seg_v3.onnx" + + if EXISTING_ONNX.exists(): + if EXISTING_ONNX.resolve() != target.resolve(): + target.write_bytes(EXISTING_ONNX.read_bytes()) + print(f"ONNX copied to: {target}") + return + + if not MODEL.exists(): + raise FileNotFoundError(f"Model checkpoint not found: {MODEL}") + require_yolo26_support() + model = YOLO(str(MODEL)) + exported = model.export( + format="onnx", + imgsz=864, + opset=17, + simplify=True, + dynamic=False, + half=False, + ) + exported_path = Path(exported) + if exported_path.resolve() != target.resolve(): + target.write_bytes(exported_path.read_bytes()) + print(f"ONNX exported to: {target}") + + +if __name__ == "__main__": + main() diff --git a/src/hik_predict_trt.cpp b/src/hik_predict_trt.cpp new file mode 100644 index 0000000..af29f8f --- /dev/null +++ b/src/hik_predict_trt.cpp @@ -0,0 +1,549 @@ +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "yolos/tasks/segmentation.hpp" + +namespace fs = std::filesystem; +using yolos::seg::Segmentation; +using yolos::seg::YOLOSegDetector; + +namespace { + +constexpr unsigned int kPixelMono8 = 0x01080001; +constexpr unsigned int kPixelBgr8 = 0x02180015; +constexpr unsigned int kPixelBayerRg8 = 0x01080009; + +struct AppConfig { + std::string enginePath = "models/yolo26_tile_seg_v3_fp16.trt"; + std::string labelsPath = "config/labels.names"; + std::string saveDir = "captures"; + std::string pixelFormat = "bgr8"; + int deviceIndex = 0; + int imgsz = 864; + int maxDet = 50; + int frameSkip = 2; + float confThreshold = 0.175f; + float iouThreshold = 0.5f; + double displayScale = 0.3; + bool resizeBeforeInfer = true; +}; + +const std::vector kClassNames = { + "crack", "glue_strip", "good", "gray_stroke", "oil", "rough" +}; + +const std::map kClassColors = { + {0, cv::Scalar(0, 0, 255)}, + {1, cv::Scalar(255, 165, 0)}, + {2, cv::Scalar(0, 255, 0)}, + {3, cv::Scalar(128, 128, 128)}, + {4, cv::Scalar(255, 255, 0)}, + {5, cv::Scalar(147, 20, 255)}, +}; + +std::string nowStamp() { + const auto now = std::chrono::system_clock::now(); + const std::time_t t = std::chrono::system_clock::to_time_t(now); + std::tm tm{}; + localtime_r(&t, &tm); + std::ostringstream oss; + oss << std::put_time(&tm, "%Y%m%d_%H%M%S"); + return oss.str(); +} + +void printUsage(const char* argv0) { + std::cout + << "Usage: " << argv0 << " [options]\n\n" + << "Options:\n" + << " --engine PATH TensorRT engine path\n" + << " --labels PATH labels.names path\n" + << " --device-index N HIK camera index (default: 0)\n" + << " --pixel-format FMT mono8, bgr8, or bayer_rg8 (default: bgr8)\n" + << " --imgsz N pre-inference max side resize (default: 864)\n" + << " --frame-skip N detect every N frames (default: 2)\n" + << " --display-scale X display resize scale (default: 0.3)\n" + << " --save-dir PATH capture output directory\n" + << " --no-resize-before-infer disable Python-compatible pre-inference resize\n" + << " --help show this help\n"; +} + +AppConfig parseArgs(int argc, char** argv) { + AppConfig cfg; + for (int i = 1; i < argc; ++i) { + const std::string arg = argv[i]; + auto requireValue = [&](const std::string& name) -> std::string { + if (i + 1 >= argc) { + throw std::runtime_error("Missing value for " + name); + } + return argv[++i]; + }; + + if (arg == "--engine") cfg.enginePath = requireValue(arg); + else if (arg == "--labels") cfg.labelsPath = requireValue(arg); + else if (arg == "--device-index") cfg.deviceIndex = std::stoi(requireValue(arg)); + else if (arg == "--pixel-format") cfg.pixelFormat = requireValue(arg); + else if (arg == "--imgsz") cfg.imgsz = std::stoi(requireValue(arg)); + else if (arg == "--frame-skip") cfg.frameSkip = std::max(1, std::stoi(requireValue(arg))); + else if (arg == "--display-scale") cfg.displayScale = std::stod(requireValue(arg)); + else if (arg == "--save-dir") cfg.saveDir = requireValue(arg); + else if (arg == "--no-resize-before-infer") cfg.resizeBeforeInfer = false; + else if (arg == "--help") { + printUsage(argv[0]); + std::exit(0); + } else { + throw std::runtime_error("Unknown option: " + arg); + } + } + return cfg; +} + +cv::Mat applyClahe(const cv::Mat& img, double clipLimit, int tileSize) { + cv::Mat lab; + cv::cvtColor(img, lab, cv::COLOR_BGR2Lab); + std::vector channels; + cv::split(lab, channels); + cv::Ptr clahe = cv::createCLAHE(clipLimit, cv::Size(tileSize, tileSize)); + clahe->apply(channels[0], channels[0]); + cv::merge(channels, lab); + cv::Mat out; + cv::cvtColor(lab, out, cv::COLOR_Lab2BGR); + return out; +} + +cv::Mat applyGamma(const cv::Mat& img, double gamma) { + cv::Mat table(1, 256, CV_8U); + const double invGamma = 1.0 / gamma; + for (int i = 0; i < 256; ++i) { + table.at(i) = cv::saturate_cast(std::pow(i / 255.0, invGamma) * 255.0); + } + cv::Mat out; + cv::LUT(img, table, out); + return out; +} + +double getBrightness(const cv::Mat& img) { + cv::Mat gray; + cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY); + return cv::mean(gray)[0]; +} + +cv::Mat cleanMask(const cv::Mat& mask, double minAreaRatio = 0.001) { + if (mask.empty()) return mask; + + cv::Mat binary; + cv::threshold(mask, binary, 127, 255, cv::THRESH_BINARY); + binary.convertTo(binary, CV_8U); + + cv::Mat labels, stats, centroids; + const int numLabels = cv::connectedComponentsWithStats(binary, labels, stats, centroids, 8); + if (numLabels <= 1) return binary; + + const int totalPixels = binary.rows * binary.cols; + const int minArea = static_cast(totalPixels * minAreaRatio); + cv::Mat cleaned = cv::Mat::zeros(binary.size(), CV_8U); + + for (int label = 1; label < numLabels; ++label) { + const int area = stats.at(label, cv::CC_STAT_AREA); + if (area >= minArea) { + cleaned.setTo(255, labels == label); + } + } + return cleaned; +} + +class HikCamera { +public: + ~HikCamera() { release(); } + + bool connect(int deviceIndex) { + MV_CC_DEVICE_INFO_LIST deviceList; + std::memset(&deviceList, 0, sizeof(deviceList)); + + const int ret = MV_CC_EnumDevices(MV_GIGE_DEVICE | MV_USB_DEVICE, &deviceList); + if (ret != MV_OK || deviceList.nDeviceNum == 0) { + std::cerr << "[ERROR] not detect camera HIK, ret=0x" << std::hex << ret << std::dec << "\n"; + return false; + } + std::cout << "detect " << deviceList.nDeviceNum << " camera(s)\n"; + + if (deviceIndex < 0 || static_cast(deviceIndex) >= deviceList.nDeviceNum) { + std::cerr << "[ERROR] Camera index " << deviceIndex << " does not exist\n"; + return false; + } + + int nRet = MV_CC_CreateHandle(&handle_, deviceList.pDeviceInfo[deviceIndex]); + if (nRet != MV_OK) { + std::cerr << "[ERROR] MV_CC_CreateHandle failed: 0x" << std::hex << nRet << std::dec << "\n"; + return false; + } + + nRet = MV_CC_OpenDevice(handle_, MV_ACCESS_Exclusive, 0); + if (nRet != MV_OK) { + std::cerr << "[ERROR] MV_CC_OpenDevice failed: 0x" << std::hex << nRet << std::dec << "\n"; + release(); + return false; + } + + open_ = true; + return true; + } + + bool setPixelFormat(const std::string& fmt) { + unsigned int pixelValue = kPixelBgr8; + if (fmt == "mono8") pixelValue = kPixelMono8; + else if (fmt == "bgr8") pixelValue = kPixelBgr8; + else if (fmt == "bayer_rg8") pixelValue = kPixelBayerRg8; + else { + std::cerr << "[ERROR] Unknown pixel format: " << fmt << "\n"; + return false; + } + + const int ret = MV_CC_SetEnumValue(handle_, "PixelFormat", pixelValue); + if (ret != MV_OK) { + std::cerr << "[WARN] Set PixelFormat to " << fmt << " failed: 0x" + << std::hex << ret << std::dec << "\n"; + return false; + } + pixelFormat_ = fmt; + std::cout << "Pixel format: " << fmt << "\n"; + return true; + } + + bool startGrabbing() { + const int ret = MV_CC_StartGrabbing(handle_); + if (ret != MV_OK) { + std::cerr << "[ERROR] MV_CC_StartGrabbing failed: 0x" << std::hex << ret << std::dec << "\n"; + return false; + } + grabbing_ = true; + return true; + } + + cv::Mat getFrame(unsigned int timeoutMs = 1000) { + MV_FRAME_OUT frame; + std::memset(&frame, 0, sizeof(frame)); + const int ret = MV_CC_GetImageBuffer(handle_, &frame, timeoutMs); + if (ret != MV_OK) return {}; + + cv::Mat image; + try { + const int h = static_cast(frame.stFrameInfo.nHeight); + const int w = static_cast(frame.stFrameInfo.nWidth); + const unsigned char* data = frame.pBufAddr; + + if (pixelFormat_ == "mono8") { + cv::Mat gray(h, w, CV_8UC1, const_cast(data)); + cv::cvtColor(gray, image, cv::COLOR_GRAY2BGR); + } else if (pixelFormat_ == "bayer_rg8") { + cv::Mat bayer(h, w, CV_8UC1, const_cast(data)); + // cv::cvtColor(bayer, image, cv::COLOR_BayerRG2BGR); + cv::cvtColor(bayer, image, cv::COLOR_BayerRG2RGB); + } else { + cv::Mat bgr(h, w, CV_8UC3, const_cast(data)); + image = bgr.clone(); + } + if (pixelFormat_ != "bgr8") image = image.clone(); + } catch (...) { + MV_CC_FreeImageBuffer(handle_, &frame); + throw; + } + + MV_CC_FreeImageBuffer(handle_, &frame); + return image; + } + + void release() { + if (handle_ != nullptr) { + if (grabbing_) { + MV_CC_StopGrabbing(handle_); + grabbing_ = false; + } + if (open_) { + MV_CC_CloseDevice(handle_); + open_ = false; + } + MV_CC_DestroyHandle(handle_); + handle_ = nullptr; + std::cout << "turn off camera.\n"; + } + } + +private: + void* handle_{nullptr}; + bool open_{false}; + bool grabbing_{false}; + std::string pixelFormat_{"bgr8"}; +}; + +class TileTrtPipeline { +public: + explicit TileTrtPipeline(AppConfig cfg) + : cfg_(std::move(cfg)), detector_(cfg_.enginePath, cfg_.labelsPath) { + fs::create_directories(cfg_.saveDir); + } + + std::vector detectFrame(const cv::Mat& frame) { + cv::Mat inferFrame = frame; + const bool resized = cfg_.resizeBeforeInfer && std::max(frame.rows, frame.cols) > cfg_.imgsz; + double scaleBack = 1.0; + if (resized) { + const double scale = static_cast(cfg_.imgsz) / std::max(frame.rows, frame.cols); + scaleBack = 1.0 / scale; + cv::resize(frame, inferFrame, cv::Size(), scale, scale, cv::INTER_AREA); + } + + std::vector results = runInference(inferFrame, cfg_.confThreshold); + if (results.empty()) { + results = runInference(applyClahe(inferFrame, 2.5, 8), 0.30f); + } + if (results.empty()) { + const double meanVal = getBrightness(inferFrame); + if (meanVal < 100.0) { + results = runInference(applyGamma(inferFrame, 0.7), 0.30f); + } else if (meanVal > 160.0) { + results = runInference(applyGamma(inferFrame, 1.3), 0.30f); + } + } + if (results.empty()) { + results = runInference(applyClahe(inferFrame, 4.0, 8), 0.08f); + results.erase(std::remove_if(results.begin(), results.end(), [](const Segmentation& seg) { + return seg.classId != 0; + }), results.end()); + } + + if (resized && !results.empty()) { + scaleResults(results, frame.size(), scaleBack); + } + + applySingleClassFilter(results); + if (static_cast(results.size()) > cfg_.maxDet) { + results.resize(cfg_.maxDet); + } + return results; + } + + cv::Mat draw(const cv::Mat& original, const std::vector& results) const { + cv::Mat result = original.clone(); + cv::Mat overlay = result.clone(); + + for (const auto& seg : results) { + const cv::Scalar color = colorFor(seg.classId); + if (!seg.mask.empty()) { + cv::Mat mask = cleanMask(seg.mask); + if (!mask.empty() && cv::countNonZero(mask) > 0) { + cv::Mat colored(result.size(), result.type(), cv::Scalar(0, 0, 0)); + colored.setTo(color, mask); + cv::addWeighted(overlay, 1.0, colored, 0.4, 0, overlay); + + std::vector> contours; + cv::findContours(mask, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE); + cv::drawContours(overlay, contours, -1, color, 2); + } + } + } + + result = overlay; + + for (const auto& seg : results) { + const cv::Scalar color = colorFor(seg.classId); + const cv::Rect rect(seg.box.x, seg.box.y, seg.box.width, seg.box.height); + cv::rectangle(result, rect, color, 2); + + const std::string label = className(seg.classId) + " " + formatScore(seg.conf); + int baseline = 0; + const cv::Size labelSize = cv::getTextSize(label, cv::FONT_HERSHEY_SIMPLEX, 0.7, 2, &baseline); + const int top = std::max(rect.y, labelSize.height + 10); + cv::rectangle(result, + cv::Point(rect.x, top - labelSize.height - 10), + cv::Point(rect.x + labelSize.width, top), + color, + cv::FILLED); + cv::putText(result, label, cv::Point(rect.x, top - 5), + cv::FONT_HERSHEY_SIMPLEX, 0.7, cv::Scalar(255, 255, 255), 2); + } + + return result; + } + + void saveCapture(const cv::Mat& original, const cv::Mat& result) const { + const std::string stamp = nowStamp(); + const fs::path origPath = fs::path(cfg_.saveDir) / (stamp + "_original.png"); + const fs::path resultPath = fs::path(cfg_.saveDir) / (stamp + "_result.png"); + cv::imwrite(origPath.string(), original); + cv::imwrite(resultPath.string(), result); + std::cout << "Saved: " << origPath << " + " << resultPath << "\n"; + } + +private: + std::vector runInference(const cv::Mat& img, float conf) { + return detector_.segment(img, conf, cfg_.iouThreshold); + } + + static void scaleResults(std::vector& results, const cv::Size& targetSize, double scaleBack) { + for (auto& seg : results) { + seg.box.x = std::clamp(static_cast(std::round(seg.box.x * scaleBack)), 0, targetSize.width - 1); + seg.box.y = std::clamp(static_cast(std::round(seg.box.y * scaleBack)), 0, targetSize.height - 1); + seg.box.width = std::clamp(static_cast(std::round(seg.box.width * scaleBack)), 1, targetSize.width - seg.box.x); + seg.box.height = std::clamp(static_cast(std::round(seg.box.height * scaleBack)), 1, targetSize.height - seg.box.y); + + if (!seg.mask.empty()) { + cv::Mat resizedMask; + cv::resize(seg.mask, resizedMask, targetSize, 0, 0, cv::INTER_NEAREST); + seg.mask = resizedMask; + } + } + } + + static void applySingleClassFilter(std::vector& results) { + results.erase(std::remove_if(results.begin(), results.end(), [](const Segmentation& seg) { + return seg.classId == 2; + }), results.end()); + + if (results.empty()) return; + + std::map bestConfByClass; + for (const auto& seg : results) { + bestConfByClass[seg.classId] = std::max(bestConfByClass[seg.classId], seg.conf); + } + if (bestConfByClass.size() <= 1) return; + + const auto best = std::max_element( + bestConfByClass.begin(), + bestConfByClass.end(), + [](const auto& a, const auto& b) { return a.second < b.second; }); + const int bestClass = best->first; + + results.erase(std::remove_if(results.begin(), results.end(), [bestClass](const Segmentation& seg) { + return seg.classId != bestClass; + }), results.end()); + } + + static cv::Scalar colorFor(int classId) { + const auto it = kClassColors.find(classId); + return it == kClassColors.end() ? cv::Scalar(255, 255, 255) : it->second; + } + + static std::string className(int classId) { + if (classId >= 0 && static_cast(classId) < kClassNames.size()) { + return kClassNames[classId]; + } + return "class_" + std::to_string(classId); + } + + static std::string formatScore(float score) { + std::ostringstream oss; + oss << std::fixed << std::setprecision(2) << score; + return oss.str(); + } + + AppConfig cfg_; + YOLOSegDetector detector_; +}; + +void printHeader(const AppConfig& cfg) { + std::cout << "============================================================\n" + << "Quartz Inspection Core - HIK TensorRT Realtime Pipeline\n" + << "============================================================\n" + << "Engine: " << cfg.enginePath << "\n" + << "Labels: " << cfg.labelsPath << "\n" + << "Conf: " << cfg.confThreshold << " | IoU: " << cfg.iouThreshold + << " | ImgSz: " << cfg.imgsz << "\n" + << "Frame skip: " << cfg.frameSkip << "\n" + << "Resize before infer: " << (cfg.resizeBeforeInfer ? "true" : "false") << "\n" + << "Pixel format: " << cfg.pixelFormat << "\n" + << "Display scale: " << cfg.displayScale << "\n" + << "ESC/q = exit | S = save img\n" + << "============================================================\n"; +} + +} // namespace + +int main(int argc, char** argv) { + try { + const AppConfig cfg = parseArgs(argc, argv); + printHeader(cfg); + + TileTrtPipeline pipeline(cfg); + HikCamera camera; + if (!camera.connect(cfg.deviceIndex)) return 1; + camera.setPixelFormat(cfg.pixelFormat); + if (!camera.startGrabbing()) return 1; + + int frameCount = 0; + int detectCount = 0; + auto fpsStart = std::chrono::steady_clock::now(); + cv::Mat lastResult; + + while (true) { + cv::Mat frame = camera.getFrame(); + if (frame.empty()) continue; + + ++frameCount; + cv::Mat result; + if (frameCount % cfg.frameSkip == 0) { + std::vector detections = pipeline.detectFrame(frame); + if (!detections.empty()) { + ++detectCount; + result = pipeline.draw(frame, detections); + + std::ostringstream summary; + for (size_t i = 0; i < detections.size(); ++i) { + if (i > 0) summary << ", "; + summary << kClassNames[std::clamp(detections[i].classId, 0, static_cast(kClassNames.size()) - 1)] + << " (" << std::fixed << std::setprecision(2) << detections[i].conf << ")"; + } + std::cout << " Frame " << frameCount << ": " << detections.size() + << " det -> " << summary.str() << "\n"; + } else { + result = frame; + } + lastResult = result.clone(); + } else { + result = lastResult.empty() ? frame : lastResult.clone(); + } + + const auto now = std::chrono::steady_clock::now(); + const double elapsed = std::chrono::duration(now - fpsStart).count(); + const double fps = elapsed > 0.0 ? frameCount / elapsed : 0.0; + + std::ostringstream info; + info << "FPS: " << std::fixed << std::setprecision(1) << fps + << " | Detected: " << detectCount << "/" << frameCount; + cv::putText(result, info.str(), cv::Point(10, 40), + cv::FONT_HERSHEY_SIMPLEX, 1.0, cv::Scalar(0, 255, 0), 2); + + cv::Mat display; + cv::resize(result, display, cv::Size(), cfg.displayScale, cfg.displayScale); + cv::imshow("Quartz Inspection Core - HIK TensorRT", display); + + const int key = cv::waitKey(1) & 0xFF; + if (key == 27 || key == 'q' || key == 'Q') break; + if (key == 's' || key == 'S') { + pipeline.saveCapture(frame, result); + } + } + + std::cout << "\n============================================================\n" + << detectCount << "/" << frameCount << " frames have detection\n" + << "============================================================\n"; + return 0; + } catch (const std::exception& e) { + std::cerr << "[ERROR] " << e.what() << "\n"; + return 1; + } +}