25 KiB
25 KiB
鸿蒙尿检试纸识别算法 - 技术方案
文档创建时间:2026-03-31 最后更新:2026-04-03 版本:v2.1 状态:已实现并集成到 NAPI,包含清晰度评估和杂物检测
一、技术架构
1.1 整体架构图
┌─────────────────────────────────────────────────────────────┐
│ 鸿蒙上层 (ArkTS/TS) │
│ ↓ N-API │
├─────────────────────────────────────────────────────────────┤
│ napi_init.cpp │
│ └── SayHello() 入口函数 │
│ ├── 解析输入参数 (ArrayBuffer) │
│ ├── 调用核心算法 │
│ └── 封装返回结果 │
├─────────────────────────────────────────────────────────────┤
│ 核心算法模块 │
│ ├── PaperRecognizer (试纸识别器) │
│ │ ├── 定位块检测 │
│ │ ├── 试纸规格匹配 │
│ │ └── 色块位置计算 │
│ ├── ColorReader (颜色读取器) │
│ │ ├── 白平衡处理 │
│ │ └── 颜色采样与转换 │
│ └── Config (配置模块) │
│ ├── PaperConfig (试纸规格配置) │
│ └── GlobalParams (全局误差参数) │
├─────────────────────────────────────────────────────────────┤
│ OpenCV 库 │
│ ├── imgproc (图像处理) │
│ ├── core (核心数据结构) │
│ └── imgcodecs (图像编解码) │
└─────────────────────────────────────────────────────────────┘
1.2 文件结构
entry/src/main/cpp/
├── docs/ # 文档目录
│ ├── 沟通日志.md
│ ├── 技术方案.md
│ └── 详细设计文档.md # 新增:详细设计文档
├── images/ # 测试图片(27张)
├── reference/ # 参考代码(老代码)
│ ├── ImgLocateDryChemistry.cpp # 老代码-参考
│ ├── ImageLocation.cpp
│ └── ...
├── test/ # Windows测试程序
│ ├── test_main.cpp # 测试入口
│ ├── build/ # 构建目录
│ └── CMakeLists.txt # 测试构建配置
├── napi_init.cpp # N-API 入口(已集成新代码)
├── napi_init_old.cpp # N-API 备份(老代码)
├── PaperRecognizer.h # 试纸识别器头文件
├── PaperRecognizer.cpp # 试纸识别器实现(核心)
├── ColorReader.h # 颜色读取器头文件
├── ColorReader.cpp # 颜色读取器实现
├── PaperConfig.h # 试纸配置定义
├── PaperConfig.cpp # 试纸配置实现
├── Types.h # 类型定义
└── CMakeLists.txt # 鸿蒙构建配置
二、核心模块设计
2.1 类型定义 (Types.h)
#pragma once
#include <opencv2/opencv.hpp>
#include <vector>
#include <string>
// 试纸联数
enum class BlockItems {
BI_14 = 14,
BI_11 = 11,
BI_8 = 8
};
// 大定位块类型
enum class BigLocatorType {
BLT_SHORT = 0, // 10mm
BLT_LONG = 1 // 15mm
};
// 定位块颜色分类
enum class LocatorColor {
UNKNOWN = 0,
RED = 1,
GREEN = 2,
BLUE = 3
};
// 试纸空间类型
enum class PaperSpatialType {
PST_UNKNOWN = 0,
PST_14_S = 1, // 14联, 10mm大定位块
PST_14_L = 2, // 14联, 15mm大定位块
PST_11_S = 3, // 11联, 10mm大定位块
PST_11_L = 4, // 11联, 15mm大定位块
PST_8_S = 5, // 8联, 10mm大定位块
PST_8_L = 6 // 8联, 15mm大定位块
};
// 图像清晰度等级(新增)
enum class BlurLevel {
BLUR_NONE = 0, // 清晰
BLUR_SLIGHT = 1, // 轻微模糊
BLUR_SEVERE = 2 // 严重模糊
};
// 定位块信息
struct LocatorInfo {
cv::RotatedRect rotatedRect; // 旋转矩形
cv::Point2f center; // 中心点
double area; // 面积
double width; // 宽度(长边)
double height; // 高度(短边)
LocatorColor color; // 颜色
bool isBig; // 是否大定位块
cv::Scalar avgColor; // 平均RGB颜色
};
// 色块颜色结果
struct ColorResult {
int id; // 编号(从靠近小定位块开始)
double h, s, v; // HSV值
double l, a, b; // LAB值
double r, g, b_val; // RGB值
};
// 识别结果
struct RecognitionResult {
bool success; // 是否成功
int errorCode; // 错误码
std::string errorMessage; // 错误信息
PaperSpatialType paperType; // 试纸类型
LocatorColor locatorColor; // 定位块颜色
int itemCount; // 色块数量
std::vector<cv::Point2f> colorBlockCenters; // 色块中心点
std::vector<ColorResult> colors; // 颜色结果
cv::Mat annotatedImage; // 标注后的图片
bool smallLocatorOnLeft; // 小定位块是否在左边
BlurLevel blurLevel; // 图像清晰度等级(新增)
double blurScore; // 清晰度分数(新增)
};
2.2 全局参数 (GlobalParams.h)
#pragma once
namespace GlobalParams {
// ========== 颜色误差 ==========
// RGB欧式距离阈值,判断两个定位块颜色是否相同
const double COLOR_DISTANCE_THRESHOLD = 20.0;
// ========== 面积误差 ==========
// 面积误差比例(10%)
const double AREA_ERROR_RATIO = 0.10;
// ========== 距离误差 ==========
// 距离误差比例(10%)
const double DISTANCE_ERROR_RATIO = 0.10;
// ========== 角度误差 ==========
// 角度误差(度)
const double ANGLE_ERROR_DEGREE = 15.0;
// ========== 定位块尺寸比例 ==========
// 大定位块(10mm)宽高比:10/5 = 2.0
const double BIG_LOCATOR_RATIO_SHORT = 2.0;
// 大定位块(15mm)宽高比:15/5 = 3.0
const double BIG_LOCATOR_RATIO_LONG = 3.0;
// 小定位块宽高比:5/3 ≈ 1.667(高度是长边)
const double SMALL_LOCATOR_RATIO = 1.667;
// ========== 面积比例 ==========
// 大定位块(10mm)与小定位块面积比:10/3 ≈ 3.33
const double AREA_RATIO_SHORT = 3.33;
// 大定位块(15mm)与小定位块面积比:15/3 = 5.0
const double AREA_RATIO_LONG = 5.0;
// ========== 采样参数 ==========
// 最小采样像素数
const int MIN_SAMPLE_PIXELS = 25;
// 默认采样半径
const int DEFAULT_SAMPLE_RADIUS = 3;
}
2.3 试纸配置 (PaperConfig)
#pragma once
#include "Types.h"
#include <map>
// 单个试纸规格配置
struct PaperConfig {
PaperSpatialType type; // 试纸类型
BlockItems blockItems; // 联数
BigLocatorType locatorType; // 大定位块类型
int itemsNum; // 反应色块数量
int slicesNum; // 最小分割单位数量
double firstPos; // 第一个色块位置倍数
double step; // 步长倍数
double distTimes; // 定位块中心距离/试纸高度
double whBigRatio; // 大定位块宽高比
double whSmallRatio; // 小定位块宽高比
};
// 试纸配置管理器
class PaperConfigManager {
public:
static PaperConfigManager& getInstance();
const PaperConfig* getConfig(PaperSpatialType type) const;
PaperSpatialType matchConfig(double distRatio, double areaRatio) const;
private:
PaperConfigManager();
void initConfigs();
std::map<PaperSpatialType, PaperConfig> configs_;
};
2.4 试纸识别器 (PaperRecognizer)
#pragma once
#include "Types.h"
#include "PaperConfig.h"
#include <opencv2/opencv.hpp>
class PaperRecognizer {
public:
PaperRecognizer();
~PaperRecognizer();
// 主识别函数
RecognitionResult recognize(const cv::Mat& image);
private:
// ===== 第一步:图像预处理 =====
void preprocessImage(const cv::Mat& image);
// ===== 第二步:定位块检测 =====
bool detectLocators();
void findCandidateContours();
bool filterLocatorCandidates();
bool validateLocatorPair();
// ===== 第三步:颜色判断 =====
LocatorColor determineLocatorColor(const cv::Mat& roi);
double calculateColorDistance(const cv::Scalar& c1, const cv::Scalar& c2);
// ===== 第四步:规格匹配 =====
bool matchPaperSpec();
// ===== 第五步:色块位置计算 =====
void calculateColorBlockCenters();
// ===== 第六步:绘制标注 =====
void drawAnnotations();
// ===== 辅助函数 =====
double calculateAspectRatio(const cv::RotatedRect& rect);
bool isBigLocator(const cv::RotatedRect& rect, double height);
private:
cv::Mat originalImage_; // 原图
cv::Mat processImage_; // 处理用图像
cv::Mat hsvImage_; // HSV图像
LocatorInfo leftLocator_; // 左定位块
LocatorInfo rightLocator_; // 右定位块
bool leftIsBig_; // 左边是否是大定位块
std::vector<cv::Point> centers_; // 色块中心点
const PaperConfig* config_; // 匹配的配置
RecognitionResult result_; // 结果
};
2.5 颜色读取器 (ColorReader)
#pragma once
#include "Types.h"
#include <opencv2/opencv.hpp>
class ColorReader {
public:
ColorReader();
~ColorReader();
// 执行颜色读取
std::vector<ColorResult> readColors(
const cv::Mat& image,
const std::vector<cv::Point>& centers,
bool smallLocatorOnLeft
);
private:
// 白平衡处理
void applyWhiteBalance(cv::Mat& image);
// 采样颜色
cv::Scalar sampleColor(const cv::Mat& image, const cv::Point& center);
// 颜色空间转换
void convertColorSpaces(const cv::Scalar& bgr,
double& h, double& s, double& v,
double& l, double& a, double& b);
// 调整顺序(始终从靠近小定位块开始)
std::vector<ColorResult> adjustOrder(
std::vector<ColorResult>& colors,
bool smallLocatorOnLeft
);
};
三、核心算法流程
3.1 主流程图
输入图像
│
▼
┌─────────────────┐
│ 1. 图像预处理 │
│ - 颜色空间转换 │
│ - 高斯滤波 │
└────────┬────────┘
│
▼
┌─────────────────┐
│ 2. 轮廓检测 │
│ - 二值化 │
│ - findContours│
└────────┬────────┘
│
▼
┌─────────────────┐
│ 3. 定位块筛选 │
│ - 面积过滤 │
│ - 宽高比过滤 │
│ - 矩形度过滤 │
└────────┬────────┘
│
▼
┌─────────────────┐
│ 4. 定位块配对 │
│ - 面积比验证 │
│ - 颜色一致性 │
│ - 距离验证 │
└────────┬────────┘
│
┌────┴────┐
│ 候选数=2? │
└────┬────┘
│
┌────┼────┐
Yes No
│ │
▼ ▼
继续 返回错误
│
▼
┌─────────────────┐
│ 5. 规格匹配 │
│ - 计算距离比 │
│ - 匹配PaperType│
└────────┬────────┘
│
▼
┌─────────────────┐
│ 6. 色块位置计算 │
│ - 计算斜率 │
│ - 计算各中心点 │
└────────┬────────┘
│
▼
┌─────────────────┐
│ 7. 颜色读取 │
│ - 白平衡 │
│ - 采样颜色 │
│ - HSV/LAB转换 │
└────────┬────────┘
│
▼
┌─────────────────┐
│ 8. 结果封装 │
│ - 绘制标注 │
│ - JSON格式 │
└─────────────────┘
│
▼
返回结果
3.2 定位块检测算法
输入: 二值化图像
输出: 2个定位块信息
Step 1: findContours 获取所有轮廓
Step 2: 遍历轮廓,计算几何特征
- 面积: contourArea()
- 最小外接矩形: minAreaRect()
- 宽高比: max(w,h) / min(w,h)
- 矩形度: area / (w * h)
Step 3: 过滤轮廓
- 面积范围: [minArea, maxArea]
- 宽高比: 大定位块 ≈ 2.0 或 3.0, 小定位块 ≈ 1.667
- 矩形度: > 0.85
Step 4: 分组配对
- 按面积分组: 大/小
- 验证面积比: 大/小 ≈ 3.33 或 5.0
- 验证颜色一致性: RGB欧式距离 < 20
Step 5: 验证距离
- 两定位块中心距离
- 与PaperConfig中distTimes匹配
返回: 两个定位块信息
3.3 色块位置计算算法
// 伪代码
void calculateColorBlockCenters() {
// 1. 获取两个定位块中心点
Point p1 = leftLocator_.center;
Point p2 = rightLocator_.center;
// 2. 计算方向向量和距离
Point vec = p2 - p1;
double totalDist = norm(vec);
Point unitVec = vec / totalDist;
// 3. 计算基准单位(像素/毫米)
// 试纸高度 = 两定位块高度的均值
double paperHeight = (leftLocator_.height + rightLocator_.height) / 2;
// 4. 根据 PaperConfig 计算每个色块位置
double avgDist = totalDist / config_->slicesNum;
double firstOffset = avgDist * config_->firstPos;
double stepOffset = avgDist * config_->step;
// 5. 计算各色块中心点
Point firstCenter = p1 + unitVec * firstOffset;
for (int i = 0; i < config_->itemsNum; i++) {
Point center = firstCenter + unitVec * (stepOffset * i);
centers_.push_back(center);
}
}
3.4 白平衡算法
参考 reference/ColorCorrection.cpp:
void applyWhiteBalance(cv::Mat& image) {
// 1. 计算各通道均值
Scalar sumChannels = sum(image);
int totalPixels = image.rows * image.cols;
double avgB = sumChannels[0] / totalPixels;
double avgG = sumChannels[1] / totalPixels;
double avgR = sumChannels[2] / totalPixels;
// 2. 计算目标均值(三通道平均)
double targetAvg = (avgB + avgG + avgR) / 3.0;
// 3. 各通道缩放校正
std::vector<Mat> channels(3);
split(image, channels);
channels[0] = channels[0] * (targetAvg / avgB);
channels[1] = channels[1] * (targetAvg / avgG);
channels[2] = channels[2] * (targetAvg / avgR);
merge(channels, image);
image.convertTo(image, CV_8UC3);
}
四、PaperConfig 参数表
4.1 支持的试纸规格
| 类型 | 联数 | 大定位块 | itemsNum | slicesNum | firstPos | step | distTimes | whBigRatio |
|---|---|---|---|---|---|---|---|---|
| PST_14_S | 14 | 10mm | 14 | 50 | 2.25 | 3.5 | 21.3 | 2.0 |
| PST_14_L | 14 | 15mm | 14 | 50 | 2.25 | 3.5 | 21.8 | 3.0 |
| PST_11_S | 11 | 10mm | 11 | 39 | 2.25 | 3.5 | 17.6 | 2.0 |
| PST_11_L | 11 | 15mm | 11 | 39 | 2.25 | 3.5 | 17.6 | 3.0 |
| PST_8_S | 8 | 10mm | 8 | 29 | 2.25 | 3.5 | 12.9 | 2.0 |
| PST_8_L | 8 | 15mm | 8 | 29 | 2.25 | 3.5 | 13.4 | 3.0 |
4.2 试纸物理尺寸参考
以 PST_14_S (14联,10mm大定位块) 为例:
- 小定位块:3mm × 5mm
- 大定位块:10mm × 5mm
- 反应色块:14个 × (5mm × 5mm)
- 间隔:15个 × 2mm
- 总长度:3 + 14×5 + 15×2 + 10 = 3 + 70 + 30 + 10 = 113mm
- 定位块中心距离:113 - 1.5 - 5 = 106.5mm
- distTimes = 106.5 / 5 = 21.3
五、测试计划
5.1 测试环境
- 操作系统:Windows
- 编译器:MSVC 或 MinGW
- OpenCV:D:\opencv(官方预编译库)
- 测试框架:自定义简单测试框架
5.2 测试图片
| 文件名 | 类型 | 说明 |
|---|---|---|
| 11green_1.png | 11联绿色 | 设计参考图 |
| 11green_2.png | 11联绿色 | 摄像头采集 |
| 14blue_1.png | 14联蓝色 | 设计参考图 |
| 14blue_2.png | 14联蓝色 | 摄像头采集 |
| 14red_1.png | 14联红色 | 设计参考图 |
| 14red_2.png | 14联红色 | 摄像头采集 |
| 65686153160b075c3d7eb019f9eecdb4.jpg | 实拍 | 实际采集 |
| be3af2fa7372464a98172a91fa52adb8.jpg | 实拍 | 实际采集 |
| ... | ... | 其他实拍图片 |
5.3 测试输出
每个测试图片生成以下输出:
-
标注图片:
{filename}_annotated.jpg- 在定位块周围画红框
- 在色块中心画红圈(半径5像素)
- 标注色块编号
-
颜色数据文件:
{filename}_colors.txtPaper Type: PST_14_S Locator Color: RED Item Count: 14 Status: SUCCESS Color Results: [0] HSV(12.34, 56.78, 90.12) LAB(23.45, 67.89, 12.34) RGB(255, 128, 64) [1] HSV(...) ... -
还原模拟图:
{filename}_restored.jpg- 200px × 1000px
- 试纸居中
- 定位块颜色按识别结果
- 色块颜色按读取结果
5.4 测试用例
| 用例ID | 描述 | 预期结果 |
|---|---|---|
| TC001 | 14联红色试纸 | 正确识别PST_14_S/R,返回14个颜色值 |
| TC002 | 14联蓝色试纸 | 正确识别PST_14_S/B,返回14个颜色值 |
| TC003 | 11联绿色试纸 | 正确识别PST_11_S/G,返回11个颜色值 |
| TC004 | 8联试纸 | 正确识别PST_8_x,返回8个颜色值 |
| TC005 | 15mm大定位块 | 正确识别PST_14_L等L型规格 |
| TC006 | 倾斜试纸 | 正确处理倾斜,色块位置准确 |
| TC007 | 小定位块在右 | 颜色顺序正确(从右往左读,结果从左往右排) |
| TC008 | 无效图片 | 返回错误码,不崩溃 |
六、实现步骤
阶段一:基础框架(Day 1)
- 创建文件结构
- 实现 Types.h 类型定义
- 实现 GlobalParams.h 全局参数
- 实现 PaperConfig 配置模块
阶段二:核心算法(Day 2-3)
-
实现 PaperRecognizer
- 图像预处理
- 轮廓检测
- 定位块筛选与配对
- 规格匹配
- 色块位置计算
-
实现 ColorReader
- 白平衡处理
- 颜色采样
- 颜色空间转换
阶段三:测试程序(Day 4)
- 创建 test/ 目录
- 实现测试入口和运行器
- 配置 CMakeLists.txt(链接 D:\opencv)
- 编写测试输出逻辑
阶段四:调试优化(Day 5)
- 运行测试,查看结果
- 调整误差参数
- 优化识别率
- 处理边界情况
阶段五:NAPI 集成(已完成 ✅)
- ✅ 修改 napi_init.cpp 的 SayHello 函数
- ✅ 更新 CMakeLists.txt(移除老文件,添加新文件)
- ✅ 编译 HAP 成功
- ✅ 实现白平衡处理
- ✅ 实现自适应 ROI 颜色采样
- ✅ 实现试纸裁剪保存(getPaperData)
阶段六:优化迭代(已完成 ✅)
- ✅ 颜色显示修复:BGRA→BGR 颜色空间转换修复
- ✅ 规格匹配优化:调整 distRatio 范围,添加缓冲区间
- ✅ 颜色一致性验证:配对定位块必须颜色相同
- ✅ 宽高比过滤:最大宽高比限制4.0,容差收紧至0.35
- ✅ 清晰度评估:Laplacian方差法检测图像模糊(新增)
- ✅ 杂物检测:试纸高度<30px或候选>15个时拒绝识别(新增)
- ✅ NAPI参数扩展:返回locatorColor、paperType、blurLevel、blurScore
七、编译与运行
7.1 测试程序编译
# Windows PowerShell
cd E:\Qoder\urologist\entry\src\main\cpp\test
mkdir build
cd build
cmake .. -DOpenCV_DIR=D:\opencv\build
cmake --build . --config Release
7.2 运行测试
# 运行单个图片测试
.\Release\test_urine_analyzer.exe ..\..\images\14red_1.png
# 运行批量测试
.\Release\test_urine_analyzer.exe ..\..\images\
7.3 查看结果
# 结果输出在 test_output/ 目录
cd ..\..\test_output
dir
八、风险与对策
| 风险 | 影响 | 对策 |
|---|---|---|
| 光照变化大 | 定位块识别失败 | 增加颜色判断的鲁棒性,提供可调参数 |
| 试纸倾斜过大 | 色块位置计算偏差 | 使用斜率补偿计算 |
| 图片质量差 | 轮廓检测失败 | 预处理增强(滤波、形态学操作) |
| 颜色相近 | 定位块配对错误 | 多重验证条件(面积、距离、颜色) |
九、附录
A. SayHello 返回值结构
{
"byteLength": 123456, // 图像数据长度
"buffer": ArrayBuffer, // 图像数据(RGBA格式)
"width": 1920, // 图像宽度
"height": 1080, // 图像高度
"strLength": 567, // 颜色字符串长度
"strBuffer": ArrayBuffer, // 颜色JSON字符串
"locatorColor": 1, // 定位块颜色:0=未知,1=红,2=绿,3=蓝(新增)
"paperType": 1, // 试纸类型:1=PST_14_S,2=PST_14_L,...(新增)
"blurLevel": 0, // 清晰度等级:0=清晰,1=轻微模糊,2=严重模糊(新增)
"blurScore": 450.5, // 清晰度分数(Laplacian方差值,新增)
"statusCode": 0 // 状态码:0成功,其他失败
}
B. 状态码定义
| 状态码 | 含义 | 说明 |
|---|---|---|
| 0 | 成功 | 识别成功,返回完整结果 |
| 1 | 未检测到定位块 | 没有找到符合条件的定位块轮廓 |
| 2 | 定位块颜色识别失败 | 定位块颜色无法识别(非红/绿/蓝) |
| 3 | 定位块配对失败 | 未找到一大一小的有效配对 |
| 4 | 试纸规格匹配失败 | distRatio 不在任何规格范围内 |
| 5 | 色块位置计算失败 | 内部计算错误 |
| 6 | 检测到多条试纸 | 图片中存在多条试纸,需单独拍摄 |
| 7 | 图像处理错误 | 图像格式或处理异常 |
| 8 | 输入图像为空 | 传入的图像数据为空 |
| 9 | 试纸太小/杂物 | 试纸高度<30px,可能是杂物干扰(新增) |
| 10 | 场景杂乱 | 候选定位块>15个,场景过于杂乱(新增) |
| 100 | 未知错误 | 其他未分类错误 |
C. 色块编号规则
核心原则:编号 0 始终是靠近小定位块的色块
无论试纸如何放置(水平、垂直、旋转),返回的颜色数据中:
id=0始终是小定位块旁边的第一个反应色块id=1,2,3...依次远离小定位块
实现方式:
calculateColorBlockCenters()始终从小定位块边缘开始计算- 方向向量始终从小定位块指向大定位块
- 这样
centers_[0]始终靠近小定位块
文档结束