image.vision\ocr\ocr_accuracy.mbt

94.2% · 130 / 138 points · 433 lines

Background color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.

  1. 1///|
  2. 2/// # OCR 精度 ocr/ocr_accuracy
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// OCR 准确率提升
  7. 7// 更多特征提取、集成学习、训练数据管理、置信度校准
  8. 8
  9. 9///|
  10. 10/// 训练样本数据集
  11. 11#derive(Eq, @debug.Debug)
  12. 12pub(all) struct TrainingDataset {
  13. 13 samples : Array[TrainingSample]
  14. 14 labels : Array[String]
  15. 15 num_samples : Int32
  16. 16 num_classes : Int32
  17. 17}
  18. 18
  19. 19///|
  20. 20pub extend TrainingDataset with Eq::{not_equal, equal}
  21. 21
  22. 22///|
  23. 23pub extend TrainingDataset with @debug.Debug::{to_repr}
  24. 24
  25. 25///|
  26. 26/// 集成分类器配置
  27. 27#derive(Eq, @debug.Debug)
  28. 28pub(all) struct EnsembleConfig {
  29. 29 use_knn : Bool
  30. 30 use_template : Bool
  31. 31 use_svm_like : Bool
  32. 32 knn_k : Int32
  33. 33 voting_method : String // "majority" / "weighted" / "confidence"
  34. 34}
  35. 35
  36. 36///|
  37. 37pub extend EnsembleConfig with Eq::{not_equal, equal}
  38. 38
  39. 39///|
  40. 40pub extend EnsembleConfig with @debug.Debug::{to_repr}
  41. 41
  42. 42///|
  43. 43/// 创建默认集成配置
  44. 44pub fn ensemble_default_config() -> EnsembleConfig {
  45. 45● EnsembleConfig::{
  46. 46 use_knn: true,
  47. 47 use_template: true,
  48. 48 use_svm_like: true,
  49. 49 knn_k: 3,
  50. 50 voting_method: "weighted",
  51. 51 }
  52. 52}
  53. 53
  54. 54///|
  55. 55/// 创建空训练数据集
  56. 56pub fn dataset_create() -> TrainingDataset {
  57. 57● TrainingDataset::{ samples: [], labels: [], num_samples: 0, num_classes: 0, }
  58. 58}
  59. 59
  60. 60///|
  61. 61/// 添加样本到数据集
  62. 62pub fn dataset_add_sample(
  63. 63 dataset : TrainingDataset,
  64. 64 features : Array[Double],
  65. 65 label : String,
  66. 66) -> TrainingDataset {
  67. 67● let new_samples = dataset.samples
  68. 68● new_samples.push(TrainingSample::{ features, label, })
  69. 69 let new_labels = dataset.labels
  70. 70 let mut found = false
  71. 71 for l in new_labels {
  72. 72● if l == label {
  73. 73● found = true
  74. 74 }
  75. 75 }
  76. 76 if !found {
  77. 77● new_labels.push(label)
  78. 78 }
  79. 79 TrainingDataset::{
  80. 80 samples: new_samples,
  81. 81 labels: new_labels,
  82. 82● num_samples: new_samples.length(),
  83. 83● num_classes: new_labels.length(),
  84. 84 }
  85. 85}
  86. 86
  87. 87///|
  88. 88/// 数据集统计信息
  89. 89pub fn dataset_stats(
  90. 90 dataset : TrainingDataset,
  91. 91) -> (Int32, Int32, Array[(String, Int32)]) {
  92. 92● let class_counts : Array[(String, Int32)] = []
  93. 93 for label in dataset.labels {
  94. 94● let mut count = 0
  95. 95 for sample in dataset.samples {
  96. 96● if sample.label == label {
  97. 97● count += 1
  98. 98 }
  99. 99 }
  100. 100● class_counts.push((label, count))
  101. 101 }
  102. 102 (dataset.num_samples, dataset.num_classes, class_counts)
  103. 103}
  104. 104
  105. 105///|
  106. 106/// 特征增广(添加噪声、缩放、平移)
  107. 107pub fn augment_features(
  108. 108 features : Array[Double],
  109. 109 noise_level~ : Double = 0.05,
  110. 110) -> Array[Double] {
  111. 111● let augmented : Array[Double] = []
  112. 112● for i in 0..<features.length() {
  113. 113 // 添加高斯噪声(简化为均匀噪声)
  114. 114● let noise = (pseudo_random(i) - 0.5) * 2.0 * noise_level
  115. 115 let new_val = features[i] + noise
  116. 116 let clamped = if new_val < 0.0 {
  117. 117● 0.0
  118. 118● } else if new_val > 1.0 {
  119. 119● 1.0
  120. 120 } else {
  121. 121● new_val
  122. 122 }
  123. 123● augmented.push(clamped)
  124. 124 }
  125. 125 augmented
  126. 126}
  127. 127
  128. 128///|
  129. 129/// 伪随机数生成(基于索引的确定性随机)
  130. 130fn pseudo_random(seed : Int32) -> Double {
  131. 131● let x = (seed * 1103515245 + 12345) % 1073741824
  132. 132● x.to_double() / 1073741824.0
  133. 133}
  134. 134
  135. 135///|
  136. 136/// Hu 矩特征(7个不变矩)
  137. 137pub fn hu_moments_features(
  138. 138 img : @types.Image,
  139. 139) -> Array[Double] raise @types.LoadError {
  140. 140 // 输入验证
  141. 141● if img.width <= 0 || img.height <= 0 {
  142. 142● raise @types.LoadError::DecodeFailed(
  143. 143 "hu_moments_features: 图像尺寸必须大于0",
  144. 144 )
  145. 145 }
  146. 146 if img.channels != 1 {
  147. 147● raise @types.LoadError::DecodeFailed(
  148. 148 "hu_moments_features: 仅支持单通道图",
  149. 149 )
  150. 150 }
  151. 151 let expected_size = img.width * img.height
  152. 152● if img.data.length() != expected_size {
  153. 153● raise @types.LoadError::DecodeFailed(
  154. 154 "hu_moments_features: 数据大小不匹配,期望 " +
  155. 155● expected_size.to_string() +
  156. 156 ",实际 " +
  157. 157● img.data.length().to_string(),
  158. 158 )
  159. 159 }
  160. 160 let w = img.width
  161. 161 let h = img.height
  162. 162 let data = img.data
  163. 163 // 计算零阶和一阶矩
  164. 164 let mut m00 = 0.0
  165. 165 let mut m10 = 0.0
  166. 166 let mut m01 = 0.0
  167. 167 for y in 0..<h {
  168. 168● for x in 0..<w {
  169. 169● let val = data[y * w + x].to_int().to_double() / 255.0
  170. 170 m00 += val
  171. 171● m10 += x.to_double() * val
  172. 172● m01 += y.to_double() * val
  173. 173 }
  174. 174 }
  175. 175 if m00 == 0.0 {
  176. 176● return [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
  177. 177 }
  178. 178 // 质心
  179. 179 let x_bar = m10 / m00
  180. 180 let y_bar = m01 / m00
  181. 181 // 计算中心矩
  182. 182 let mut mu20 = 0.0
  183. 183 let mut mu02 = 0.0
  184. 184 let mut mu11 = 0.0
  185. 185 let mut mu30 = 0.0
  186. 186 let mut mu03 = 0.0
  187. 187 let mut mu21 = 0.0
  188. 188 let mut mu12 = 0.0
  189. 189 for y in 0..<h {
  190. 190● for x in 0..<w {
  191. 191● let val = data[y * w + x].to_int().to_double() / 255.0
  192. 192● let dx = x.to_double() - x_bar
  193. 193● let dy = y.to_double() - y_bar
  194. 194 mu20 += dx * dx * val
  195. 195 mu02 += dy * dy * val
  196. 196 mu11 += dx * dy * val
  197. 197 mu30 += dx * dx * dx * val
  198. 198 mu03 += dy * dy * dy * val
  199. 199 mu21 += dx * dx * dy * val
  200. 200 mu12 += dx * dy * dy * val
  201. 201 }
  202. 202 }
  203. 203 // 归一化中心矩
  204. 204 let eta20 = mu20 / (m00 * m00)
  205. 205 let eta02 = mu02 / (m00 * m00)
  206. 206 let eta11 = mu11 / (m00 * m00)
  207. 207 let eta30 = mu30 /
  208. 208● (m00 * m00 * m00 * m00 * m00 * m00 * m00 * m00 * m00 * m00).sqrt()
  209. 209 let eta03 = mu03 /
  210. 210● (m00 * m00 * m00 * m00 * m00 * m00 * m00 * m00 * m00 * m00).sqrt()
  211. 211 let eta21 = mu21 /
  212. 212● (m00 * m00 * m00 * m00 * m00 * m00 * m00 * m00 * m00 * m00).sqrt()
  213. 213 let eta12 = mu12 /
  214. 214● (m00 * m00 * m00 * m00 * m00 * m00 * m00 * m00 * m00 * m00).sqrt()
  215. 215 // Hu 不变矩
  216. 216 let h1 = eta20 + eta02
  217. 217 let h2 = (eta20 - eta02) * (eta20 - eta02) + 4.0 * eta11 * eta11
  218. 218 let h3 = (eta30 - 3.0 * eta12) * (eta30 - 3.0 * eta12) +
  219. 219 (3.0 * eta21 - eta03) * (3.0 * eta21 - eta03)
  220. 220 let h4 = (eta30 + eta12) * (eta30 + eta12) + (eta21 + eta03) * (eta21 + eta03)
  221. 221 let h5 = (eta30 - 3.0 * eta12) *
  222. 222 (eta30 + eta12) *
  223. 223 (
  224. 224 (eta30 + eta12) * (eta30 + eta12) -
  225. 225 3.0 * (eta21 + eta03) * (eta21 + eta03)
  226. 226 ) +
  227. 227 (3.0 * eta21 - eta03) *
  228. 228 (eta21 + eta03) *
  229. 229 (
  230. 230 3.0 * (eta30 + eta12) * (eta30 + eta12) -
  231. 231 (eta21 + eta03) * (eta21 + eta03)
  232. 232 )
  233. 233 let h6 = (eta20 - eta02) *
  234. 234 ((eta30 + eta12) * (eta30 + eta12) - (eta21 + eta03) * (eta21 + eta03)) +
  235. 235 4.0 * eta11 * (eta30 + eta12) * (eta21 + eta03)
  236. 236 let h7 = (3.0 * eta21 - eta03) *
  237. 237 (eta30 + eta12) *
  238. 238 (
  239. 239 (eta30 + eta12) * (eta30 + eta12) -
  240. 240 3.0 * (eta21 + eta03) * (eta21 + eta03)
  241. 241 ) -
  242. 242 (eta30 - 3.0 * eta12) *
  243. 243 (eta21 + eta03) *
  244. 244 (
  245. 245 3.0 * (eta30 + eta12) * (eta30 + eta12) -
  246. 246 (eta21 + eta03) * (eta21 + eta03)
  247. 247 )
  248. 248 [h1, h2, h3, h4, h5, h6, h7]
  249. 249}
  250. 250
  251. 251///|
  252. 252/// 集成分类器预测(多分类器投票)
  253. 253pub fn ensemble_predict(
  254. 254 features : Array[Double],
  255. 255 knn_classifier : KnnClassifier,
  256. 256 templates : Array[(String, Array[Double])],
  257. 257 config? : EnsembleConfig,
  258. 258) -> ClassificationResult raise @types.LoadError {
  259. 259 // 输入验证
  260. 260● if features.length() == 0 {
  261. 261● raise @types.LoadError::DecodeFailed(
  262. 262 "ensemble_predict: 特征向量不能为空",
  263. 263 )
  264. 264 }
  265. 265
  266. 266● let cfg = match config {
  267. 267● Some(c) => c
  268. 268● None => ensemble_default_config()
  269. 269 }
  270. 270 // 收集所有分类器的预测
  271. 271 let predictions : Array[(String, Double)] = []
  272. 272 // KNN 预测
  273. 273 if cfg.use_knn {
  274. 274● let knn_result = knn_predict(knn_classifier, features) catch {
  275. 275○ _ => ClassificationResult::{ label: "?", confidence: 0.0, top_k: [], }
  276. 276 }
  277. 277● predictions.push((knn_result.label, knn_result.confidence))
  278. 278 }
  279. 279 // 模板匹配预测
  280. 280 if cfg.use_template {
  281. 281● let mut best_label = "?"
  282. 282 let mut best_dist = 1000000.0
  283. 283 for _tup0 in templates {
  284. 284● let (label, template) = _tup0
  285. 285● let dist = euclidean_distance_ensemble(features, template)
  286. 286 if dist < best_dist {
  287. 287● best_dist = dist
  288. 288 best_label = label
  289. 289 }
  290. 290 }
  291. 291◐ let confidence = if best_dist > 0.0 { 1.0 / (1.0 + best_dist) } else { 1.0 }
  292. 292● predictions.push((best_label, confidence))
  293. 293 }
  294. 294 // SVM-like 预测(简化版:基于距离的线性分类)
  295. 295 if cfg.use_svm_like {
  296. 296 // 简化:使用最近邻作为SVM-like预测
  297. 297● if templates.length() > 0 {
  298. 298● let mut best_label = "?"
  299. 299 let mut best_dist = 1000000.0
  300. 300 for _tup1 in templates {
  301. 301● let (label, template) = _tup1
  302. 302● let dist = manhattan_distance_ensemble(features, template)
  303. 303 if dist < best_dist {
  304. 304● best_dist = dist
  305. 305 best_label = label
  306. 306 }
  307. 307 }
  308. 308 let confidence = if best_dist > 0.0 {
  309. 309● 1.0 / (1.0 + best_dist)
  310. 310 } else {
  311. 311○ 1.0
  312. 312 }
  313. 313● predictions.push((best_label, confidence))
  314. 314 }
  315. 315 }
  316. 316 // 投票
  317. 317 let label_votes : Array[(String, Double)] = []
  318. 318 for _tup2 in predictions {
  319. 319● let (label, conf) = _tup2
  320. 320 let mut found = false
  321. 321● for i in 0..<label_votes.length() {
  322. 322● if label_votes[i].0 == label {
  323. 323● let weight = match cfg.voting_method {
  324. 324● "majority" => 1.0
  325. 325● "confidence" => conf
  326. 326● _ => conf
  327. 327 }
  328. 328 label_votes[i] = (label, label_votes[i].1 + weight)
  329. 329 found = true
  330. 330 }
  331. 331 }
  332. 332 if !found {
  333. 333● let weight = match cfg.voting_method {
  334. 334● "majority" => 1.0
  335. 335● "confidence" => conf
  336. 336● _ => conf
  337. 337 }
  338. 338● label_votes.push((label, weight))
  339. 339 }
  340. 340 }
  341. 341 // 找得票最多的标签
  342. 342 let mut best_label = "?"
  343. 343 let mut best_votes = 0.0
  344. 344 for _tup3 in label_votes {
  345. 345● let (label, votes) = _tup3
  346. 346 if votes > best_votes {
  347. 347● best_votes = votes
  348. 348 best_label = label
  349. 349 }
  350. 350 }
  351. 351● let total_votes = if predictions.length() > 0 {
  352. 352● predictions.length().to_double()
  353. 353 } else {
  354. 354○ 1.0
  355. 355 }
  356. 356 let confidence = best_votes / total_votes
  357. 357 ClassificationResult::{ label: best_label, confidence, top_k: predictions, }
  358. 358}
  359. 359
  360. 360///|
  361. 361/// 局部欧氏距离
  362. 362fn euclidean_distance_ensemble(a : Array[Double], b : Array[Double]) -> Double {
  363. 363◐ let n = if a.length() < b.length() { a.length() } else { b.length() }
  364. 364 let mut sum_sq = 0.0
  365. 365 for i in 0..<n {
  366. 366● let diff = a[i] - b[i]
  367. 367 sum_sq += diff * diff
  368. 368 }
  369. 369● sum_sq.sqrt()
  370. 370}
  371. 371
  372. 372///|
  373. 373/// 局部曼哈顿距离
  374. 374fn manhattan_distance_ensemble(a : Array[Double], b : Array[Double]) -> Double {
  375. 375◐ let n = if a.length() < b.length() { a.length() } else { b.length() }
  376. 376 let mut sum = 0.0
  377. 377 for i in 0..<n {
  378. 378● sum += (a[i] - b[i]).abs()
  379. 379 }
  380. 380 sum
  381. 381}
  382. 382
  383. 383///|
  384. 384/// 组合多种特征(网格+HOG+LBP+Hu矩)
  385. 385pub fn extract_combined_ocr_features(
  386. 386 img : @types.Image,
  387. 387) -> Array[Double] raise @types.LoadError {
  388. 388 // 输入验证
  389. 389● if img.width <= 0 || img.height <= 0 {
  390. 390● raise @types.LoadError::DecodeFailed(
  391. 391 "extract_combined_ocr_features: 图像尺寸必须大于0",
  392. 392 )
  393. 393 }
  394. 394 if img.channels != 1 {
  395. 395● raise @types.LoadError::DecodeFailed(
  396. 396 "extract_combined_ocr_features: 仅支持单通道灰度图",
  397. 397 )
  398. 398 }
  399. 399 let expected_size = img.width * img.height
  400. 400● if img.data.length() != expected_size {
  401. 401● raise @types.LoadError::DecodeFailed(
  402. 402 "extract_combined_ocr_features: 数据大小不匹配,期望 " +
  403. 403● expected_size.to_string() +
  404. 404 ",实际 " +
  405. 405● img.data.length().to_string(),
  406. 406 )
  407. 407 }
  408. 408 // 网格特征
  409. 409● let grid = grid_features(img, grid_rows=8, grid_cols=8)
  410. 410 // HOG 特征
  411. 411● let hog = hog_features(img, cell_size=8, num_bins=9)
  412. 412 // LBP 特征(降采样)
  413. 413● let lbp = lbp_features(img, radius=1, num_points=8, num_bins=64)
  414. 414 // Hu 矩特征
  415. 415● let hu = hu_moments_features(img)
  416. 416 // 组合
  417. 417 let combined : Array[Double] = []
  418. 418 for f in grid.features {
  419. 419● combined.push(f)
  420. 420 }
  421. 421 for f in hog.features {
  422. 422● combined.push(f)
  423. 423 }
  424. 424● for i in 0..<lbp.features.length() {
  425. 425● if i < 64 {
  426. 426● combined.push(lbp.features[i])
  427. 427 }
  428. 428 }
  429. 429 for f in hu {
  430. 430● combined.push(f)
  431. 431 }
  432. 432 combined
  433. 433}