#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; } }