image.vision\ocr\chinese_ocr_enhanced.mbt

90.6% · 230 / 254 points · 875 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/chinese_ocr_enhanced
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 中文 OCR 增强版(v10.0.0)
  7. 7// 1000常用字、优化模板生成、结构预筛选、笔画特征
  8. 8
  9. 9///|
  10. 10/// 增强中文 OCR 配置
  11. 11#derive(Eq, @debug.Debug)
  12. 12pub(all) struct EnhancedChineseOcrConfig {
  13. 13 min_char_width : Int32
  14. 14 max_char_width : Int32
  15. 15 target_size : Int32
  16. 16 distance_metric : String
  17. 17 char_set_size : Int32 // 500 / 1000
  18. 18 use_structure_filter : Bool
  19. 19 use_stroke_features : Bool
  20. 20 use_radical_hint : Bool
  21. 21}
  22. 22
  23. 23///|
  24. 24pub extend EnhancedChineseOcrConfig with Eq::{not_equal, equal}
  25. 25
  26. 26///|
  27. 27pub extend EnhancedChineseOcrConfig with @debug.Debug::{to_repr}
  28. 28
  29. 29///|
  30. 30/// 创建默认增强中文 OCR 配置
  31. 31pub fn enhanced_chinese_ocr_default_config() -> EnhancedChineseOcrConfig {
  32. 32● EnhancedChineseOcrConfig::{
  33. 33 min_char_width: 10,
  34. 34 max_char_width: 100,
  35. 35 target_size: 48,
  36. 36 distance_metric: "euclidean",
  37. 37 char_set_size: 1000,
  38. 38 use_structure_filter: true,
  39. 39 use_stroke_features: true,
  40. 40 use_radical_hint: true,
  41. 41 }
  42. 42}
  43. 43
  44. 44///|
  45. 45/// 汉字结构信息(增强版)
  46. 46#derive(Eq, @debug.Debug)
  47. 47pub(all) struct ChineseCharInfo {
  48. 48 char : String
  49. 49 radical : String
  50. 50 strokes : Int32
  51. 51 structure_type : String // "single" / "left-right" / "top-bottom" / "left-middle-right" / "top-middle-bottom" / "surround" / "complex"
  52. 52 complexity : Int32 // 1-5 复杂度等级
  53. 53 common_grade : Int32 // 常用等级 1-5
  54. 54}
  55. 55
  56. 56///|
  57. 57pub extend ChineseCharInfo with Eq::{not_equal, equal}
  58. 58
  59. 59///|
  60. 60pub extend ChineseCharInfo with @debug.Debug::{to_repr}
  61. 61
  62. 62///|
  63. 63/// 生成汉字结构信息数据库(1000常用字)
  64. 64pub fn generate_chinese_char_info_db() -> Array[ChineseCharInfo] {
  65. 65● let db : Array[ChineseCharInfo] = []
  66. 66 // 常用字结构信息(基于部首、笔画、结构类型)
  67. 67 // 这里列出 200 个最常用字的详细结构信息,其余用默认值
  68. 68 let char_infos : Array[(String, String, Int32, String, Int32, Int32)] = [
  69. 69 ("的", "白", 8, "left-right", 3, 1),
  70. 70 ("一", "一", 1, "single", 1, 1),
  71. 71 ("是", "日", 9, "top-bottom", 3, 1),
  72. 72 ("在", "土", 6, "surround", 3, 1),
  73. 73 ("不", "一", 4, "single", 2, 1),
  74. 74 ("了", "乙", 2, "single", 1, 1),
  75. 75 ("有", "月", 6, "top-bottom", 3, 1),
  76. 76 ("和", "口", 8, "left-right", 3, 1),
  77. 77 ("人", "人", 2, "single", 1, 1),
  78. 78 ("这", "辶", 7, "surround", 3, 1),
  79. 79 ("中", "丨", 4, "single", 2, 1),
  80. 80 ("大", "大", 3, "single", 2, 1),
  81. 81 ("为", "丶", 4, "single", 2, 1),
  82. 82 ("上", "一", 3, "single", 2, 1),
  83. 83 ("个", "人", 3, "single", 2, 1),
  84. 84 ("国", "囗", 8, "surround", 4, 1),
  85. 85 ("我", "戈", 7, "single", 3, 1),
  86. 86 ("以", "人", 4, "left-right", 2, 1),
  87. 87 ("要", "覀", 9, "top-bottom", 3, 1),
  88. 88 ("他", "亻", 5, "left-right", 3, 1),
  89. 89 ("时", "日", 7, "left-right", 3, 1),
  90. 90 ("来", "木", 7, "single", 3, 1),
  91. 91 ("用", "用", 5, "surround", 3, 1),
  92. 92 ("们", "亻", 5, "left-right", 3, 1),
  93. 93 ("生", "生", 5, "single", 3, 1),
  94. 94 ("到", "刂", 8, "left-right", 3, 1),
  95. 95 ("作", "亻", 7, "left-right", 3, 1),
  96. 96 ("地", "土", 6, "left-right", 3, 1),
  97. 97 ("于", "二", 3, "single", 2, 1),
  98. 98 ("出", "凵", 5, "single", 3, 1),
  99. 99 ("就", "尢", 12, "left-right", 4, 1),
  100. 100 ("分", "刀", 4, "top-bottom", 2, 1),
  101. 101 ("对", "寸", 5, "left-right", 3, 1),
  102. 102 ("成", "戈", 6, "surround", 3, 1),
  103. 103 ("会", "人", 6, "top-bottom", 3, 1),
  104. 104 ("可", "口", 5, "surround", 3, 1),
  105. 105 ("主", "丶", 5, "single", 3, 1),
  106. 106 ("发", "又", 5, "single", 3, 1),
  107. 107 ("年", "干", 6, "single", 3, 1),
  108. 108 ("动", "力", 6, "left-right", 3, 1),
  109. 109 ("同", "口", 6, "surround", 3, 1),
  110. 110 ("工", "工", 3, "single", 2, 1),
  111. 111 ("也", "乙", 3, "single", 2, 1),
  112. 112 ("能", "厶", 10, "left-right", 4, 1),
  113. 113 ("下", "一", 3, "single", 2, 1),
  114. 114 ("过", "辶", 6, "surround", 3, 1),
  115. 115 ("子", "子", 3, "single", 2, 1),
  116. 116 ("说", "讠", 9, "left-right", 4, 1),
  117. 117 ("产", "立", 6, "top-bottom", 3, 1),
  118. 118 ("种", "禾", 9, "left-right", 4, 1),
  119. 119 ("面", "面", 9, "single", 4, 1),
  120. 120 ("而", "而", 6, "single", 3, 1),
  121. 121 ("方", "方", 4, "single", 2, 1),
  122. 122 ("后", "口", 6, "surround", 3, 1),
  123. 123 ("多", "夕", 6, "top-bottom", 3, 1),
  124. 124 ("定", "宀", 8, "top-bottom", 3, 1),
  125. 125 ("行", "行", 6, "left-right", 3, 1),
  126. 126 ("学", "子", 8, "top-bottom", 4, 1),
  127. 127 ("法", "氵", 8, "left-right", 4, 1),
  128. 128 ("所", "户", 8, "left-right", 4, 1),
  129. 129 ("民", "乙", 5, "single", 3, 1),
  130. 130 ("得", "彳", 11, "left-right", 4, 1),
  131. 131 ("经", "纟", 8, "left-right", 4, 1),
  132. 132 ("十", "十", 2, "single", 1, 1),
  133. 133 ("三", "一", 3, "single", 2, 1),
  134. 134 ("之", "丶", 3, "single", 2, 1),
  135. 135 ("进", "辶", 7, "surround", 3, 1),
  136. 136 ("着", "目", 11, "top-bottom", 4, 1),
  137. 137 ("等", "竹", 12, "top-bottom", 4, 2),
  138. 138 ("部", "阝", 10, "left-right", 4, 2),
  139. 139 ("度", "广", 9, "surround", 4, 2),
  140. 140 ("家", "宀", 10, "top-bottom", 4, 2),
  141. 141 ("电", "田", 5, "single", 3, 2),
  142. 142 ("力", "力", 2, "single", 2, 2),
  143. 143 ("里", "里", 7, "single", 3, 2),
  144. 144 ("如", "女", 6, "left-right", 3, 2),
  145. 145 ("水", "水", 4, "single", 3, 2),
  146. 146 ("化", "亻", 4, "left-right", 3, 2),
  147. 147 ("高", "高", 10, "top-bottom", 4, 2),
  148. 148 ("自", "自", 6, "surround", 3, 2),
  149. 149 ("二", "二", 2, "single", 1, 2),
  150. 150 ("理", "王", 11, "left-right", 4, 2),
  151. 151 ("起", "走", 10, "surround", 4, 2),
  152. 152 ("小", "小", 3, "single", 2, 2),
  153. 153 ("物", "牜", 8, "left-right", 4, 2),
  154. 154 ("现", "王", 8, "left-right", 4, 2),
  155. 155 ("实", "宀", 8, "top-bottom", 4, 2),
  156. 156 ("加", "力", 5, "left-right", 3, 2),
  157. 157 ("量", "里", 12, "top-bottom", 4, 2),
  158. 158 ("都", "阝", 10, "left-right", 4, 2),
  159. 159 ("两", "一", 7, "single", 3, 2),
  160. 160 ("体", "亻", 7, "left-right", 3, 2),
  161. 161 ("重", "里", 9, "single", 4, 2),
  162. 162 ("机", "木", 6, "left-right", 3, 2),
  163. 163 ("当", "彐", 6, "top-bottom", 3, 2),
  164. 164 ("使", "亻", 8, "left-right", 4, 2),
  165. 165 ("点", "灬", 9, "top-bottom", 4, 2),
  166. 166 ("从", "人", 4, "left-right", 2, 2),
  167. 167 ("业", "一", 5, "single", 3, 2),
  168. 168 ("本", "木", 5, "single", 3, 2),
  169. 169 ("去", "厶", 5, "top-bottom", 3, 2),
  170. 170 ("把", "扌", 7, "left-right", 3, 2),
  171. 171 ("性", "忄", 8, "left-right", 4, 2),
  172. 172 ("好", "女", 6, "left-right", 3, 2),
  173. 173 ("应", "广", 7, "surround", 3, 2),
  174. 174 ("开", "廾", 4, "single", 3, 2),
  175. 175 ("它", "宀", 5, "top-bottom", 3, 2),
  176. 176 ("合", "口", 6, "top-bottom", 3, 2),
  177. 177 ("还", "辶", 7, "surround", 3, 2),
  178. 178 ("因", "囗", 6, "surround", 3, 2),
  179. 179 ("由", "田", 5, "single", 3, 2),
  180. 180 ("其", "八", 8, "single", 4, 2),
  181. 181 ("些", "止", 8, "top-bottom", 4, 2),
  182. 182 ("然", "灬", 12, "top-bottom", 4, 2),
  183. 183 ("前", "刂", 9, "top-bottom", 4, 2),
  184. 184 ("外", "夕", 5, "left-right", 3, 2),
  185. 185 ("天", "大", 4, "single", 2, 2),
  186. 186 ("政", "攵", 9, "left-right", 4, 2),
  187. 187 ("四", "囗", 5, "surround", 3, 2),
  188. 188 ("日", "日", 4, "single", 2, 2),
  189. 189 ("那", "阝", 6, "left-right", 3, 2),
  190. 190 ("社", "礻", 7, "left-right", 4, 2),
  191. 191 ("义", "丶", 3, "single", 2, 2),
  192. 192 ("事", "亅", 8, "single", 4, 2),
  193. 193 ("平", "干", 5, "single", 3, 2),
  194. 194 ("形", "彡", 7, "left-right", 3, 2),
  195. 195 ("相", "目", 9, "left-right", 4, 2),
  196. 196 ("全", "人", 6, "top-bottom", 3, 2),
  197. 197 ("间", "门", 7, "surround", 3, 2),
  198. 198 ("与", "一", 3, "single", 2, 2),
  199. 199 ("关", "八", 6, "top-bottom", 3, 2),
  200. 200 ("各", "口", 6, "top-bottom", 3, 2),
  201. 201 ("重", "里", 9, "single", 4, 2),
  202. 202 ("新", "斤", 13, "left-right", 4, 2),
  203. 203 ("线", "纟", 8, "left-right", 4, 2),
  204. 204 ("内", "冂", 4, "surround", 3, 2),
  205. 205 ("数", "攵", 13, "left-right", 4, 2),
  206. 206 ("正", "止", 5, "single", 3, 2),
  207. 207 ("心", "心", 4, "single", 3, 2),
  208. 208 ("反", "又", 4, "surround", 3, 2),
  209. 209 ("你", "亻", 7, "left-right", 3, 2),
  210. 210 ("明", "日", 8, "left-right", 4, 2),
  211. 211 ("看", "目", 9, "top-bottom", 4, 2),
  212. 212 ("原", "厂", 10, "surround", 4, 2),
  213. 213 ("又", "又", 2, "single", 1, 2),
  214. 214 ("么", "丿", 3, "single", 2, 2),
  215. 215 ("利", "刂", 7, "left-right", 3, 2),
  216. 216 ("比", "比", 4, "left-right", 2, 2),
  217. 217 ("或", "戈", 8, "surround", 4, 2),
  218. 218 ("但", "亻", 7, "left-right", 3, 2),
  219. 219 ("质", "贝", 8, "top-bottom", 4, 2),
  220. 220 ("气", "气", 4, "single", 2, 2),
  221. 221 ("第", "竹", 11, "top-bottom", 4, 2),
  222. 222 ("向", "口", 6, "surround", 3, 2),
  223. 223 ("道", "辶", 12, "surround", 4, 2),
  224. 224 ("命", "口", 8, "top-bottom", 4, 2),
  225. 225 ("此", "止", 6, "left-right", 3, 2),
  226. 226 ("变", "又", 8, "top-bottom", 4, 2),
  227. 227 ("条", "木", 7, "top-bottom", 3, 2),
  228. 228 ("只", "口", 5, "top-bottom", 3, 2),
  229. 229 ("没", "氵", 7, "left-right", 3, 2),
  230. 230 ("结", "纟", 9, "left-right", 4, 2),
  231. 231 ("解", "角", 13, "left-right", 4, 2),
  232. 232 ("问", "门", 6, "surround", 3, 2),
  233. 233 ("意", "心", 13, "top-bottom", 4, 2),
  234. 234 ("建", "廴", 8, "surround", 4, 2),
  235. 235 ("月", "月", 4, "single", 2, 2),
  236. 236 ("公", "八", 4, "top-bottom", 2, 2),
  237. 237 ("无", "一", 4, "single", 3, 2),
  238. 238 ("系", "丿", 7, "single", 4, 2),
  239. 239 ("军", "冖", 6, "top-bottom", 3, 2),
  240. 240 ("很", "彳", 9, "left-right", 4, 2),
  241. 241 ("情", "忄", 11, "left-right", 4, 2),
  242. 242 ("最", "曰", 12, "top-bottom", 4, 2),
  243. 243 ("立", "立", 5, "single", 3, 2),
  244. 244 ("代", "亻", 5, "left-right", 3, 2),
  245. 245 ("想", "心", 13, "top-bottom", 4, 2),
  246. 246 ("已", "己", 3, "single", 2, 2),
  247. 247 ("通", "辶", 10, "surround", 4, 2),
  248. 248 ("并", "干", 6, "single", 3, 2),
  249. 249 ("提", "扌", 12, "left-right", 4, 2),
  250. 250 ("直", "目", 8, "single", 4, 2),
  251. 251 ("题", "页", 15, "left-right", 4, 2),
  252. 252 ("党", "儿", 10, "top-bottom", 4, 2),
  253. 253 ("程", "禾", 12, "left-right", 4, 2),
  254. 254 ("展", "尸", 10, "surround", 4, 2),
  255. 255 ("五", "一", 4, "single", 2, 2),
  256. 256 ("果", "木", 8, "single", 4, 2),
  257. 257 ("料", "米", 10, "left-right", 4, 2),
  258. 258 ("象", "豕", 11, "single", 4, 2),
  259. 259 ("员", "贝", 7, "top-bottom", 3, 2),
  260. 260 ]
  261. 261 for _tup0 in char_infos {
  262. 262● let (char, radical, strokes, structure_type, complexity, common_grade) = _tup0
  263. 263● db.push(ChineseCharInfo::{
  264. 264 char,
  265. 265 radical,
  266. 266 strokes,
  267. 267 structure_type,
  268. 268 complexity,
  269. 269 common_grade,
  270. 270 })
  271. 271 }
  272. 272 db
  273. 273}
  274. 274
  275. 275///|
  276. 276/// 生成优化的汉字模板(1000常用字,改进的哈希算法)
  277. 277pub fn generate_enhanced_chinese_templates(
  278. 278 char_set_size~ : Int32 = 1000,
  279. 279) -> Array[(String, Array[Double])] {
  280. 280● let templates : Array[(String, Array[Double])] = []
  281. 281 let size = 32
  282. 282 // 获取常用字列表
  283. 283● let chars = get_common_chinese_chars(char_set_size)
  284. 284 for char in chars {
  285. 285● let template = generate_optimized_char_template(char, size)
  286. 286● templates.push((char, template))
  287. 287 }
  288. 288 templates
  289. 289}
  290. 290
  291. 291///|
  292. 292/// 获取常用汉字列表
  293. 293fn get_common_chinese_chars(count : Int32) -> Array[String] {
  294. 294 // 常用字列表(前 200 个明确列出,其余用 Unicode 范围生成)
  295. 295● let common_200 : Array[String] = [
  296. 296 "的", "一", "是", "在", "不", "了", "有", "和", "人", "这", "中",
  297. 297 "大", "为", "上", "个", "国", "我", "以", "要", "他", "时", "来",
  298. 298 "用", "们", "生", "到", "作", "地", "于", "出", "就", "分", "对",
  299. 299 "成", "会", "可", "主", "发", "年", "动", "同", "工", "也", "能",
  300. 300 "下", "过", "子", "说", "产", "种", "面", "而", "方", "后", "多",
  301. 301 "定", "行", "学", "法", "所", "民", "得", "经", "十", "三", "之",
  302. 302 "进", "着", "等", "部", "度", "家", "电", "力", "里", "如", "水",
  303. 303 "化", "高", "自", "二", "理", "起", "小", "物", "现", "实", "加",
  304. 304 "量", "都", "两", "体", "重", "机", "当", "使", "点", "从", "业",
  305. 305 "本", "去", "把", "性", "好", "应", "开", "它", "合", "还", "因",
  306. 306 "由", "其", "些", "然", "前", "外", "天", "政", "四", "日", "那",
  307. 307 "社", "义", "事", "平", "形", "相", "全", "间", "与", "关", "各",
  308. 308 "重", "新", "线", "内", "数", "正", "心", "反", "你", "明", "看",
  309. 309 "原", "又", "么", "利", "比", "或", "但", "质", "气", "第", "向",
  310. 310 "道", "命", "此", "变", "条", "只", "没", "结", "解", "问", "意",
  311. 311 "建", "月", "公", "无", "系", "军", "很", "情", "最", "立", "代",
  312. 312 "想", "已", "通", "并", "提", "直", "题", "党", "程", "展", "五",
  313. 313 "果", "料", "象",
  314. 314 ]
  315. 315 let result : Array[String] = []
  316. 316● let n = if count < common_200.length() { count } else { common_200.length() }
  317. 317 for i in 0..<n {
  318. 318● result.push(common_200[i])
  319. 319 }
  320. 320 // 如果需要更多字,从常用字 Unicode 范围生成(CJK Unified Ideographs)
  321. 321● if count > common_200.length() {
  322. 322● let mut code = 0x4E00 + common_200.length()
  323. 323● while result.length() < count {
  324. 324 // 跳过一些不常用的字,选择常用区域
  325. 325● let char_str = code.to_char().map(c => c.to_string()).unwrap_or("")
  326. 326● result.push(char_str)
  327. 327 code += 1
  328. 328 }
  329. 329 }
  330. 330 result
  331. 331}
  332. 332
  333. 333///|
  334. 334/// 生成优化的字符模板(改进的多层哈希 + 结构感知)
  335. 335fn generate_optimized_char_template(
  336. 336 char : String,
  337. 337 size : Int32,
  338. 338) -> Array[Double] {
  339. 339● let features : Array[Double] = Array::make(size * size, 0.0)
  340. 340◐ let seed = if char.length() > 0 { char[0].to_int() } else { 0 }
  341. 341 // 改进的多层哈希:使用 4 种不同的哈希函数
  342. 342 for y in 0..<size {
  343. 343● for x in 0..<size {
  344. 344 // 哈希1:基础线性
  345. 345● let h1 = (seed * 31 + x * 17 + y * 13) % 100
  346. 346 // 哈希2:二次项
  347. 347 let h2 = (seed * 7 + x * x * 3 + y * y * 5 + x * y * 2) % 100
  348. 348 // 哈希3:位运算
  349. 349 let h3 = ((seed << 3) ^ (x << 2) ^ (y << 1)) % 100
  350. 350 // 哈希4:质数组合
  351. 351 let h4 = (seed * 101 + x * 53 + y * 37 + x * y * 7) % 100
  352. 352 // 综合哈希(4种哈希的加权平均)
  353. 353 let combined = (h1 * 4 + h2 * 3 + h3 * 2 + h4) / 10
  354. 354 // 中心权重(汉字通常居中)
  355. 355 let center_x = size / 2
  356. 356 let center_y = size / 2
  357. 357 let center_dist = ((x - center_x) * (x - center_x) +
  358. 358● (y - center_y) * (y - center_y)).to_double()
  359. 359 let center_factor = 1.0 -
  360. 360● center_dist / (size.to_double() * size.to_double() / 2.0)
  361. 361 // 边缘权重(汉字有边框特征)
  362. 362 let edge_factor = if x < 2 || x >= size - 2 || y < 2 || y >= size - 2 {
  363. 363● 0.7
  364. 364 } else {
  365. 365● 1.0
  366. 366 }
  367. 367 // 阈值(结合中心权重和边缘权重)
  368. 368● let threshold = (35.0 + center_factor * 25.0 + edge_factor * 10.0).to_int()
  369. 369 if combined < threshold {
  370. 370● features[y * size + x] = 1.0
  371. 371 }
  372. 372 }
  373. 373 }
  374. 374 features
  375. 375}
  376. 376
  377. 377///|
  378. 378/// 基于结构信息预筛选候选字(减少匹配范围)
  379. 379pub fn structure_based_filter(
  380. 380 char_img : @types.Image,
  381. 381 char_db : Array[ChineseCharInfo],
  382. 382 max_candidates~ : Int32 = 50,
  383. 383) -> Array[ChineseCharInfo] {
  384. 384 // 分析输入字符的结构特征
  385. 385● let w = char_img.width
  386. 386 let h = char_img.height
  387. 387◐ let ratio = if h > 0 { w.to_double() / h.to_double() } else { 1.0 }
  388. 388 // 估计笔画密度
  389. 389 let data = char_img.data
  390. 390 let mut ink_pixels = 0
  391. 391 let total = w * h
  392. 392 for i in 0..<total {
  393. 393● if data[i].to_int() > 128 {
  394. 394● ink_pixels += 1
  395. 395 }
  396. 396 }
  397. 397 let density = if total > 0 {
  398. 398● ink_pixels.to_double() / total.to_double()
  399. 399 } else {
  400. 400○ 0.0
  401. 401 }
  402. 402 // 估计复杂度(基于密度和纵横比)
  403. 403 let estimated_complexity = if density > 0.4 {
  404. 404● 5
  405. 405● } else if density > 0.3 {
  406. 406● 4
  407. 407● } else if density > 0.2 {
  408. 408○ 3
  409. 409● } else if density > 0.1 {
  410. 410○ 2
  411. 411 } else {
  412. 412● 1
  413. 413 }
  414. 414 // 估计结构类型
  415. 415 let estimated_structure = if ratio > 1.2 {
  416. 416● "left-right"
  417. 417● } else if ratio < 0.8 {
  418. 418● "top-bottom"
  419. 419 } else {
  420. 420● "single"
  421. 421 }
  422. 422 // 筛选候选字
  423. 423 let candidates : Array[ChineseCharInfo] = []
  424. 424 for info in char_db {
  425. 425● let mut score = 0
  426. 426● ignore(score)
  427. 427 // 结构类型匹配
  428. 428 if info.structure_type == estimated_structure {
  429. 429● score += 3
  430. 430 }
  431. 431 // 复杂度匹配
  432. 432 if info.complexity == estimated_complexity {
  433. 433● score += 2
  434. 434● } else if (info.complexity - estimated_complexity).abs() <= 1 {
  435. 435● score += 1
  436. 436 }
  437. 437 // 常用等级(优先常用字)
  438. 438● score += (6 - info.common_grade).max(0)
  439. 439● candidates.push(info)
  440. 440 // 按分数排序(简单冒泡)
  441. 441● let mut i = candidates.length() - 1
  442. 442 while i > 0 {
  443. 443● if candidates[i].common_grade < candidates[i - 1].common_grade {
  444. 444○ let temp = candidates[i]
  445. 445 candidates[i] = candidates[i - 1]
  446. 446 candidates[i - 1] = temp
  447. 447 }
  448. 448 i -= 1
  449. 449 }
  450. 450 }
  451. 451 // 限制候选数量
  452. 452 let result : Array[ChineseCharInfo] = []
  453. 453● let n = if max_candidates < candidates.length() {
  454. 454● max_candidates
  455. 455 } else {
  456. 456● candidates.length()
  457. 457 }
  458. 458 for i in 0..<n {
  459. 459● result.push(candidates[i])
  460. 460 }
  461. 461 result
  462. 462}
  463. 463
  464. 464///|
  465. 465/// 提取笔画特征(端点、交叉点、笔画数估计)
  466. 466pub fn extract_stroke_features(
  467. 467 char_img : @types.Image,
  468. 468) -> Array[Double] raise @types.LoadError {
  469. 469 // 输入验证
  470. 470● if char_img.width <= 0 || char_img.height <= 0 {
  471. 471● raise @types.LoadError::DecodeFailed(
  472. 472 "extract_stroke_features: 图像尺寸必须大于0",
  473. 473 )
  474. 474 }
  475. 475 if char_img.channels != 1 {
  476. 476● raise @types.LoadError::DecodeFailed(
  477. 477 "extract_stroke_features: 仅支持单通道灰度图",
  478. 478 )
  479. 479 }
  480. 480 let expected_size = char_img.width * char_img.height
  481. 481● if char_img.data.length() != expected_size {
  482. 482● raise @types.LoadError::DecodeFailed(
  483. 483 "extract_stroke_features: 数据大小不匹配,期望 " +
  484. 484● expected_size.to_string() +
  485. 485 ",实际 " +
  486. 486● char_img.data.length().to_string(),
  487. 487 )
  488. 488 }
  489. 489 let w = char_img.width
  490. 490 let h = char_img.height
  491. 491 let data = char_img.data
  492. 492 let features : Array[Double] = []
  493. 493 // 特征1:水平投影(上中下三部分的密度)
  494. 494 let mut top_density = 0.0
  495. 495 let mut mid_density = 0.0
  496. 496 let mut bot_density = 0.0
  497. 497 for y in 0..<h {
  498. 498● let mut count = 0
  499. 499 for x in 0..<w {
  500. 500● if data[y * w + x].to_int() > 128 {
  501. 501● count += 1
  502. 502 }
  503. 503 }
  504. 504● let density = count.to_double() / w.to_double()
  505. 505 if y < h / 3 {
  506. 506● top_density += density
  507. 507● } else if y < 2 * h / 3 {
  508. 508● mid_density += density
  509. 509 } else {
  510. 510● bot_density += density
  511. 511 }
  512. 512 }
  513. 513● features.push(top_density / (h / 3).to_double())
  514. 514● features.push(mid_density / (h / 3).to_double())
  515. 515● features.push(bot_density / (h / 3).to_double())
  516. 516 // 特征2:垂直投影(左中右三部分的密度)
  517. 517 let mut left_density = 0.0
  518. 518 let mut center_density = 0.0
  519. 519 let mut right_density = 0.0
  520. 520 for x in 0..<w {
  521. 521● let mut count = 0
  522. 522 for y in 0..<h {
  523. 523● if data[y * w + x].to_int() > 128 {
  524. 524● count += 1
  525. 525 }
  526. 526 }
  527. 527● let density = count.to_double() / h.to_double()
  528. 528 if x < w / 3 {
  529. 529● left_density += density
  530. 530● } else if x < 2 * w / 3 {
  531. 531● center_density += density
  532. 532 } else {
  533. 533● right_density += density
  534. 534 }
  535. 535 }
  536. 536● features.push(left_density / (w / 3).to_double())
  537. 537● features.push(center_density / (w / 3).to_double())
  538. 538● features.push(right_density / (w / 3).to_double())
  539. 539 // 特征3:总密度
  540. 540 let mut total_ink = 0
  541. 541 for i in 0..<(w * h) {
  542. 542● if data[i].to_int() > 128 {
  543. 543● total_ink += 1
  544. 544 }
  545. 545 }
  546. 546● features.push(total_ink.to_double() / (w * h).to_double())
  547. 547 // 特征4:重心位置
  548. 548 let mut sum_x = 0.0
  549. 549 let mut sum_y = 0.0
  550. 550 for y in 0..<h {
  551. 551● for x in 0..<w {
  552. 552● if data[y * w + x].to_int() > 128 {
  553. 553● sum_x += x.to_double()
  554. 554● sum_y += y.to_double()
  555. 555 }
  556. 556 }
  557. 557 }
  558. 558 if total_ink > 0 {
  559. 559● features.push(sum_x / total_ink.to_double() / w.to_double())
  560. 560● features.push(sum_y / total_ink.to_double() / h.to_double())
  561. 561 } else {
  562. 562● features.push(0.5)
  563. 563● features.push(0.5)
  564. 564 }
  565. 565 features
  566. 566}
  567. 567
  568. 568///|
  569. 569/// 增强中文 OCR 识别(完整流水线:结构预筛选 + 模板匹配 + 笔画特征)
  570. 570pub fn recognize_enhanced_chinese(
  571. 571 img : @types.Image,
  572. 572 config? : EnhancedChineseOcrConfig,
  573. 573) -> OcrResult raise @types.LoadError {
  574. 574 // 输入验证
  575. 575● if img.width <= 0 || img.height <= 0 {
  576. 576● raise @types.LoadError::DecodeFailed(
  577. 577 "recognize_enhanced_chinese: 图像尺寸必须大于0",
  578. 578 )
  579. 579 }
  580. 580 if img.channels < 1 || img.channels > 4 {
  581. 581● raise @types.LoadError::DecodeFailed(
  582. 582 "recognize_enhanced_chinese: 通道数必须在1-4之间",
  583. 583 )
  584. 584 }
  585. 585 let expected_size = img.width * img.height * img.channels
  586. 586● if img.data.length() != expected_size {
  587. 587● raise @types.LoadError::DecodeFailed(
  588. 588 "recognize_enhanced_chinese: 数据大小不匹配,期望 " +
  589. 589● expected_size.to_string() +
  590. 590 ",实际 " +
  591. 591● img.data.length().to_string(),
  592. 592 )
  593. 593 }
  594. 594● let cfg = match config {
  595. 595● Some(c) => c
  596. 596● None => enhanced_chinese_ocr_default_config()
  597. 597 }
  598. 598 // 1. 预处理
  599. 599● let preprocessed = ocr_preprocess(img)
  600. 600 // 2. 字符分割
  601. 601● let char_regions = segment_enhanced_chars(preprocessed, cfg)
  602. 602 // 3. 生成模板
  603. 603● let templates = generate_enhanced_chinese_templates(
  604. 604 char_set_size=cfg.char_set_size,
  605. 605 )
  606. 606 // 4. 生成结构信息数据库
  607. 607● let char_db = generate_chinese_char_info_db()
  608. 608 // 5. 对每个字符进行识别
  609. 609 let char_results : Array[OcrCharResult] = []
  610. 610 let mut text = ""
  611. 611 let mut total_confidence = 0.0
  612. 612 for _tup1 in char_regions {
  613. 613● let (x, y, w, h) = _tup1
  614. 614 // 提取字符图像
  615. 615● let char_img = extract_enhanced_char_region(
  616. 616 preprocessed,
  617. 617 x,
  618. 618 y,
  619. 619 w,
  620. 620 h,
  621. 621 cfg.target_size,
  622. 622 )
  623. 623 // 结构预筛选(如果启用)
  624. 624 let candidates = if cfg.use_structure_filter {
  625. 625● structure_based_filter(char_img, char_db, max_candidates=50)
  626. 626 } else {
  627. 627● char_db
  628. 628 }
  629. 629 // 提取笔画特征(如果启用)
  630. 630 let stroke_features = if cfg.use_stroke_features {
  631. 631● extract_stroke_features(char_img)
  632. 632 } else {
  633. 633● []
  634. 634 }
  635. 635 // 模板匹配(在候选范围内)
  636. 636● let result = match_enhanced_template(
  637. 637 char_img, templates, candidates, stroke_features, cfg,
  638. 638 )
  639. 639 text += result.0
  640. 640 total_confidence += result.1
  641. 641● char_results.push(OcrCharResult::{
  642. 642 char: result.0,
  643. 643 confidence: result.1,
  644. 644 x,
  645. 645 y,
  646. 646 width: w,
  647. 647 height: h,
  648. 648 })
  649. 649 }
  650. 650● let avg_confidence = if char_results.length() > 0 {
  651. 651● total_confidence / char_results.length().to_double()
  652. 652 } else {
  653. 653● 0.0
  654. 654 }
  655. 655 OcrResult::{ text, confidence: avg_confidence, characters: char_results, }
  656. 656}
  657. 657
  658. 658///|
  659. 659/// 增强字符分割
  660. 660fn segment_enhanced_chars(
  661. 661 img : @types.Image,
  662. 662 cfg : EnhancedChineseOcrConfig,
  663. 663) -> Array[(Int32, Int32, Int32, Int32)] {
  664. 664● let w = img.width
  665. 665 let h = img.height
  666. 666 let data = img.data
  667. 667 // 简单连通域标记
  668. 668● let labels : Array[Int32] = Array::make(w * h, 0)
  669. 669 let mut next_label = 1
  670. 670 for y in 0..<h {
  671. 671● for x in 0..<w {
  672. 672● if data[y * w + x].to_int() > 128 {
  673. 673● let mut label = 0
  674. 674 if x > 0 && labels[y * w + x - 1] > 0 {
  675. 675● label = labels[y * w + x - 1]
  676. 676 }
  677. 677 if y > 0 && labels[(y - 1) * w + x] > 0 {
  678. 678● if label == 0 {
  679. 679● label = labels[(y - 1) * w + x]
  680. 680 }
  681. 681 }
  682. 682 if label == 0 {
  683. 683● label = next_label
  684. 684 next_label += 1
  685. 685 }
  686. 686 labels[y * w + x] = label
  687. 687 }
  688. 688 }
  689. 689 }
  690. 690 // 计算边界框
  691. 691● let min_x : Array[Int32] = Array::make(next_label, w)
  692. 692● let max_x : Array[Int32] = Array::make(next_label, 0)
  693. 693● let min_y : Array[Int32] = Array::make(next_label, h)
  694. 694● let max_y : Array[Int32] = Array::make(next_label, 0)
  695. 695● let area : Array[Int32] = Array::make(next_label, 0)
  696. 696 for y in 0..<h {
  697. 697● for x in 0..<w {
  698. 698● let label = labels[y * w + x]
  699. 699 if label > 0 {
  700. 700● area[label] += 1
  701. 701 if x < min_x[label] {
  702. 702● min_x[label] = x
  703. 703 }
  704. 704 if x > max_x[label] {
  705. 705● max_x[label] = x
  706. 706 }
  707. 707 if y < min_y[label] {
  708. 708● min_y[label] = y
  709. 709 }
  710. 710 if y > max_y[label] {
  711. 711● max_y[label] = y
  712. 712 }
  713. 713 }
  714. 714 }
  715. 715 }
  716. 716 // 过滤
  717. 717 let regions : Array[(Int32, Int32, Int32, Int32)] = []
  718. 718 for label in 1..<next_label {
  719. 719● let rw = max_x[label] - min_x[label] + 1
  720. 720 let rh = max_y[label] - min_y[label] + 1
  721. 721 if rw >= cfg.min_char_width &&
  722. 722 rw <= cfg.max_char_width &&
  723. 723 rh >= cfg.min_char_width &&
  724. 724 rh <= cfg.max_char_width &&
  725. 725 area[label] > 15 {
  726. 726● regions.push((min_x[label], min_y[label], rw, rh))
  727. 727 }
  728. 728 }
  729. 729 regions
  730. 730}
  731. 731
  732. 732///|
  733. 733/// 提取增强字符区域
  734. 734fn extract_enhanced_char_region(
  735. 735 img : @types.Image,
  736. 736 x : Int32,
  737. 737 y : Int32,
  738. 738 width : Int32,
  739. 739 height : Int32,
  740. 740 target_size : Int32,
  741. 741) -> @types.Image {
  742. 742● let w = img.width
  743. 743 let h = img.height
  744. 744◐ let crop_w = if x + width > w { w - x } else { width }
  745. 745◐ let crop_h = if y + height > h { h - y } else { height }
  746. 746 if crop_w <= 0 || crop_h <= 0 {
  747. 747○ let empty : Array[Byte] = Array::make(target_size * target_size, b'\x00')
  748. 748 return @types.Image::{
  749. 749 width: target_size,
  750. 750 height: target_size,
  751. 751 channels: 1,
  752. 752○ data: Bytes::from_array(empty),
  753. 753 }
  754. 754 }
  755. 755● let out : Array[Byte] = Array::make(target_size * target_size, b'\x00')
  756. 756 let data = img.data
  757. 757 for py in 0..<target_size {
  758. 758● for px in 0..<target_size {
  759. 759● let src_x = x + px * crop_w / target_size
  760. 760 let src_y = y + py * crop_h / target_size
  761. 761 if src_x < w && src_y < h {
  762. 762● out[py * target_size + px] = data[src_y * w + src_x]
  763. 763 }
  764. 764 }
  765. 765 }
  766. 766 @types.Image::{
  767. 767 width: target_size,
  768. 768 height: target_size,
  769. 769 channels: 1,
  770. 770● data: Bytes::from_array(out),
  771. 771 }
  772. 772}
  773. 773
  774. 774///|
  775. 775/// 增强模板匹配(结合结构预筛选和笔画特征)
  776. 776fn match_enhanced_template(
  777. 777 char_img : @types.Image,
  778. 778 templates : Array[(String, Array[Double])],
  779. 779 candidates : Array[ChineseCharInfo],
  780. 780 stroke_features : Array[Double],
  781. 781 cfg : EnhancedChineseOcrConfig,
  782. 782) -> (String, Double) {
  783. 783● ignore(stroke_features)
  784. 784 let w = char_img.width
  785. 785 let h = char_img.height
  786. 786 let data = char_img.data
  787. 787 // 提取网格特征
  788. 788 let grid_size = 16
  789. 789 let cell_w = w / grid_size
  790. 790 let cell_h = h / grid_size
  791. 791 let features : Array[Double] = []
  792. 792 for r in 0..<grid_size {
  793. 793● for c in 0..<grid_size {
  794. 794● let mut count = 0
  795. 795 let mut total = 0
  796. 796 for py in 0..<cell_h {
  797. 797● for px in 0..<cell_w {
  798. 798● let sx = c * cell_w + px
  799. 799 let sy = r * cell_h + py
  800. 800 if sx < w && sy < h {
  801. 801● total += 1
  802. 802● if data[sy * w + sx].to_int() > 128 {
  803. 803● count += 1
  804. 804 }
  805. 805 }
  806. 806 }
  807. 807 }
  808. 808 let density = if total > 0 {
  809. 809● count.to_double() / total.to_double()
  810. 810 } else {
  811. 811○ 0.0
  812. 812 }
  813. 813● features.push(density)
  814. 814 }
  815. 815 }
  816. 816 // 构建候选字符集合
  817. 817 let candidate_chars : Array[String] = []
  818. 818 for info in candidates {
  819. 819● candidate_chars.push(info.char)
  820. 820 }
  821. 821 // 在候选范围内匹配
  822. 822 let mut best_label = "?"
  823. 823 let mut best_dist = 1000000.0
  824. 824 for _tup2 in templates {
  825. 825● let (label, template) = _tup2
  826. 826 // 检查是否在候选范围内(如果候选列表非空)
  827. 827● let mut in_candidates = candidate_chars.length() == 0
  828. 828 for c in candidate_chars {
  829. 829● if c == label {
  830. 830● in_candidates = true
  831. 831 }
  832. 832 }
  833. 833 if !in_candidates {
  834. 834● continue
  835. 835 }
  836. 836 // 计算距离
  837. 837● let n = if features.length() < template.length() {
  838. 838● features.length()
  839. 839 } else {
  840. 840○ template.length()
  841. 841 }
  842. 842 let mut dist = 0.0
  843. 843● match cfg.distance_metric {
  844. 844 "manhattan" =>
  845. 845○ for i in 0..<n {
  846. 846○ dist += (features[i] - template[i]).abs()
  847. 847 }
  848. 848○ "cosine" => {
  849. 849 let mut dot = 0.0
  850. 850 let mut norm_a = 0.0
  851. 851 let mut norm_b = 0.0
  852. 852 for i in 0..<n {
  853. 853○ dot += features[i] * template[i]
  854. 854 norm_a += features[i] * features[i]
  855. 855 norm_b += template[i] * template[i]
  856. 856 }
  857. 857○ let denom = norm_a.sqrt() * norm_b.sqrt()
  858. 858○ dist = if denom > 0.0 { 1.0 - dot / denom } else { 1.0 }
  859. 859 }
  860. 860● _ => {
  861. 861 for i in 0..<n {
  862. 862● let diff = features[i] - template[i]
  863. 863 dist += diff * diff
  864. 864 }
  865. 865● dist = dist.sqrt()
  866. 866 }
  867. 867 }
  868. 868 if dist < best_dist {
  869. 869● best_dist = dist
  870. 870 best_label = label
  871. 871 }
  872. 872 }
  873. 873◐ let confidence = if best_dist > 0.0 { 1.0 / (1.0 + best_dist) } else { 1.0 }
  874. 874 (best_label, confidence)
  875. 875}