image.vision\ocr\binarization.mbt

77.6% · 83 / 107 points · 314 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/binarization
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// OCR 专用二值化算法
  7. 7// Sauvola 阈值、Niblack 阈值、OCR 自适应阈值
  8. 8
  9. 9///|
  10. 10/// 辅助函数:限制字节范围
  11. 11fn _clamp_byte_ocr(v : Int32) -> Byte {
  12. 12○ if v < 0 {
  13. 13○ b'\x00'
  14. 14○ } else if v > 255 {
  15. 15○ b'\xFF'
  16. 16 } else {
  17. 17○ v.to_byte()
  18. 18 }
  19. 19}
  20. 20
  21. 21///|
  22. 22/// 辅助函数:计算局部窗口的均值和标准差
  23. 23fn local_mean_std(
  24. 24 data : Array[Int32],
  25. 25 width : Int32,
  26. 26 height : Int32,
  27. 27 x : Int32,
  28. 28 y : Int32,
  29. 29 radius : Int32,
  30. 30) -> (Double, Double) {
  31. 31● let mut sum = 0.0
  32. 32 let mut sum_sq = 0.0
  33. 33 let mut count = 0
  34. 34 for dy in -radius..<(radius + 1) {
  35. 35● for dx in -radius..<(radius + 1) {
  36. 36● let nx = x + dx
  37. 37 let ny = y + dy
  38. 38 if nx >= 0 && nx < width && ny >= 0 && ny < height {
  39. 39● let v = data[ny * width + nx].to_double()
  40. 40 sum += v
  41. 41 sum_sq += v * v
  42. 42 count += 1
  43. 43 }
  44. 44 }
  45. 45 }
  46. 46 if count == 0 {
  47. 47○ return (0.0, 0.0)
  48. 48 }
  49. 49● let mean = sum / count.to_double()
  50. 50● let variance = sum_sq / count.to_double() - mean * mean
  51. 51◐ let std = if variance < 0.0 { 0.0 } else { variance.sqrt() }
  52. 52 (mean, std)
  53. 53}
  54. 54
  55. 55///|
  56. 56/// Niblack 局部阈值二值化
  57. 57/// 自适应阈值 T(x,y) = mean(x,y) + k * std(x,y)
  58. 58/// k: 修正系数,通常 -0.2
  59. 59/// window_size: 局部窗口大小(奇数)
  60. 60pub fn niblack_threshold(
  61. 61 img : @types.Image,
  62. 62 window_size~ : Int32 = 15,
  63. 63 k~ : Double = -0.2,
  64. 64) -> @types.Image raise @types.LoadError {
  65. 65 // 输入验证
  66. 66● if img.width <= 0 || img.height <= 0 {
  67. 67● raise @types.LoadError::DecodeFailed(
  68. 68 "niblack_threshold: 图像尺寸必须大于0",
  69. 69 )
  70. 70 }
  71. 71 if img.channels != 1 {
  72. 72● raise @types.LoadError::DecodeFailed(
  73. 73 "niblack_threshold: 仅支持单通道灰度图",
  74. 74 )
  75. 75 }
  76. 76 let expected_size = img.width * img.height
  77. 77● if img.data.length() != expected_size {
  78. 78○ raise @types.LoadError::DecodeFailed(
  79. 79 "niblack_threshold: 数据大小不匹配,期望 " +
  80. 80○ expected_size.to_string() +
  81. 81 ",实际 " +
  82. 82○ img.data.length().to_string(),
  83. 83 )
  84. 84 }
  85. 85 if window_size <= 0 || window_size % 2 == 0 {
  86. 86● raise @types.LoadError::DecodeFailed(
  87. 87 "niblack_threshold: window_size必须为正奇数",
  88. 88 )
  89. 89 }
  90. 90
  91. 91 let w = img.width
  92. 92 let h = img.height
  93. 93 let radius = window_size / 2
  94. 94 // 转换为 Int 数组
  95. 95● let data : Array[Int32] = Array::make(w * h, 0)
  96. 96 for i in 0..<(w * h) {
  97. 97● data[i] = img.data[i].to_int()
  98. 98 }
  99. 99● let out : Array[Byte] = Array::make(w * h, b'\x00')
  100. 100 for y in 0..<h {
  101. 101● for x in 0..<w {
  102. 102● let (mean, std) = local_mean_std(data, w, h, x, y, radius)
  103. 103 let threshold = mean + k * std
  104. 104● let v = data[y * w + x].to_double()
  105. 105● out[y * w + x] = if v > threshold { b'\xFF' } else { b'\x00' }
  106. 106 }
  107. 107 }
  108. 108 @types.Image::{
  109. 109 width: w,
  110. 110 height: h,
  111. 111 channels: 1,
  112. 112● data: Bytes::from_array(out),
  113. 113 }
  114. 114}
  115. 115
  116. 116///|
  117. 117/// Sauvola 局部阈值二值化(Niblack 的改进版,适合文档图像)
  118. 118/// 自适应阈值 T(x,y) = mean(x,y) * (1 + k * (std(x,y)/R - 1))
  119. 119/// k: 修正系数,通常 0.5
  120. 120/// R: 标准差的动态范围,通常 128
  121. 121/// window_size: 局部窗口大小(奇数)
  122. 122pub fn sauvola_threshold(
  123. 123 img : @types.Image,
  124. 124 window_size~ : Int32 = 15,
  125. 125 k~ : Double = 0.5,
  126. 126 r~ : Double = 128.0,
  127. 127) -> @types.Image raise @types.LoadError {
  128. 128 // 输入验证
  129. 129● if img.width <= 0 || img.height <= 0 {
  130. 130● raise @types.LoadError::DecodeFailed(
  131. 131 "sauvola_threshold: 图像尺寸必须大于0",
  132. 132 )
  133. 133 }
  134. 134 if img.channels != 1 {
  135. 135● raise @types.LoadError::DecodeFailed(
  136. 136 "sauvola_threshold: 仅支持单通道灰度图",
  137. 137 )
  138. 138 }
  139. 139 let expected_size = img.width * img.height
  140. 140● if img.data.length() != expected_size {
  141. 141○ raise @types.LoadError::DecodeFailed(
  142. 142 "sauvola_threshold: 数据大小不匹配,期望 " +
  143. 143○ expected_size.to_string() +
  144. 144 ",实际 " +
  145. 145○ img.data.length().to_string(),
  146. 146 )
  147. 147 }
  148. 148 if window_size <= 0 || window_size % 2 == 0 {
  149. 149● raise @types.LoadError::DecodeFailed(
  150. 150 "sauvola_threshold: window_size必须为正奇数",
  151. 151 )
  152. 152 }
  153. 153 if r <= 0.0 {
  154. 154● raise @types.LoadError::DecodeFailed("sauvola_threshold: r必须大于0")
  155. 155 }
  156. 156
  157. 157 let w = img.width
  158. 158 let h = img.height
  159. 159 let radius = window_size / 2
  160. 160 // 转换为 Int 数组
  161. 161● let data : Array[Int32] = Array::make(w * h, 0)
  162. 162 for i in 0..<(w * h) {
  163. 163● data[i] = img.data[i].to_int()
  164. 164 }
  165. 165● let out : Array[Byte] = Array::make(w * h, b'\x00')
  166. 166 for y in 0..<h {
  167. 167● for x in 0..<w {
  168. 168● let (mean, std) = local_mean_std(data, w, h, x, y, radius)
  169. 169 let threshold = mean * (1.0 + k * (std / r - 1.0))
  170. 170● let v = data[y * w + x].to_double()
  171. 171● out[y * w + x] = if v > threshold { b'\xFF' } else { b'\x00' }
  172. 172 }
  173. 173 }
  174. 174 @types.Image::{
  175. 175 width: w,
  176. 176 height: h,
  177. 177 channels: 1,
  178. 178● data: Bytes::from_array(out),
  179. 179 }
  180. 180}
  181. 181
  182. 182///|
  183. 183/// OCR 专用自适应阈值(结合全局阈值和局部阈值)
  184. 184/// 适用于光照不均匀的文档图像
  185. 185pub fn adaptive_threshold_ocr(
  186. 186 img : @types.Image,
  187. 187 block_size~ : Int32 = 15,
  188. 188 c~ : Int32 = 10,
  189. 189) -> @types.Image raise @types.LoadError {
  190. 190 // 输入验证
  191. 191● if img.width <= 0 || img.height <= 0 {
  192. 192● raise @types.LoadError::DecodeFailed(
  193. 193 "adaptive_threshold_ocr: 图像尺寸必须大于0",
  194. 194 )
  195. 195 }
  196. 196 if img.channels != 1 {
  197. 197● raise @types.LoadError::DecodeFailed(
  198. 198 "adaptive_threshold_ocr: 仅支持单通道灰度图",
  199. 199 )
  200. 200 }
  201. 201 let expected_size = img.width * img.height
  202. 202● if img.data.length() != expected_size {
  203. 203○ raise @types.LoadError::DecodeFailed(
  204. 204 "adaptive_threshold_ocr: 数据大小不匹配,期望 " +
  205. 205○ expected_size.to_string() +
  206. 206 ",实际 " +
  207. 207○ img.data.length().to_string(),
  208. 208 )
  209. 209 }
  210. 210 if block_size <= 0 || block_size % 2 == 0 {
  211. 211● raise @types.LoadError::DecodeFailed(
  212. 212 "adaptive_threshold_ocr: block_size必须为正奇数",
  213. 213 )
  214. 214 }
  215. 215
  216. 216 let w = img.width
  217. 217 let h = img.height
  218. 218 let radius = block_size / 2
  219. 219 // 转换为 Int 数组
  220. 220● let data : Array[Int32] = Array::make(w * h, 0)
  221. 221 for i in 0..<(w * h) {
  222. 222● data[i] = img.data[i].to_int()
  223. 223 }
  224. 224● let out : Array[Byte] = Array::make(w * h, b'\x00')
  225. 225 for y in 0..<h {
  226. 226● for x in 0..<w {
  227. 227 // 计算局部均值
  228. 228● let (mean, _) = local_mean_std(data, w, h, x, y, radius)
  229. 229● let threshold = mean - c.to_double()
  230. 230● let v = data[y * w + x].to_double()
  231. 231● out[y * w + x] = if v > threshold { b'\xFF' } else { b'\x00' }
  232. 232 }
  233. 233 }
  234. 234 @types.Image::{
  235. 235 width: w,
  236. 236 height: h,
  237. 237 channels: 1,
  238. 238● data: Bytes::from_array(out),
  239. 239 }
  240. 240}
  241. 241
  242. 242///|
  243. 243/// Otsu 全局阈值二值化(自动计算最佳阈值)
  244. 244pub fn otsu_threshold(
  245. 245 img : @types.Image,
  246. 246) -> @types.Image raise @types.LoadError {
  247. 247 // 输入验证
  248. 248● if img.width <= 0 || img.height <= 0 {
  249. 249● raise @types.LoadError::DecodeFailed(
  250. 250 "otsu_threshold: 图像尺寸必须大于0",
  251. 251 )
  252. 252 }
  253. 253 if img.channels != 1 {
  254. 254● raise @types.LoadError::DecodeFailed(
  255. 255 "otsu_threshold: 仅支持单通道灰度图",
  256. 256 )
  257. 257 }
  258. 258 let expected_size = img.width * img.height
  259. 259● if img.data.length() != expected_size {
  260. 260○ raise @types.LoadError::DecodeFailed(
  261. 261 "otsu_threshold: 数据大小不匹配,期望 " +
  262. 262○ expected_size.to_string() +
  263. 263 ",实际 " +
  264. 264○ img.data.length().to_string(),
  265. 265 )
  266. 266 }
  267. 267
  268. 268 let w = img.width
  269. 269 let h = img.height
  270. 270 let n = w * h
  271. 271 // 计算直方图
  272. 272● let histogram : Array[Int32] = Array::make(256, 0)
  273. 273 for i in 0..<n {
  274. 274● histogram[img.data[i].to_int()] += 1
  275. 275 }
  276. 276 // 计算 Otsu 最佳阈值
  277. 277 let mut sum = 0
  278. 278 for t in 0..<256 {
  279. 279● sum += t * histogram[t]
  280. 280 }
  281. 281 let mut sum_b = 0
  282. 282 let mut w_b = 0
  283. 283 let mut max_variance = 0.0
  284. 284 let mut threshold = 128
  285. 285 for t in 0..<256 {
  286. 286● w_b += histogram[t]
  287. 287 if w_b == 0 {
  288. 288● continue
  289. 289 }
  290. 290 let w_f = n - w_b
  291. 291 if w_f == 0 {
  292. 292● break
  293. 293 }
  294. 294 sum_b += t * histogram[t]
  295. 295● let m_b = sum_b.to_double() / w_b.to_double()
  296. 296● let m_f = (sum - sum_b).to_double() / w_f.to_double()
  297. 297● let variance = w_b.to_double() * w_f.to_double() * (m_b - m_f) * (m_b - m_f)
  298. 298 if variance > max_variance {
  299. 299● max_variance = variance
  300. 300 threshold = t
  301. 301 }
  302. 302 }
  303. 303 // 应用阈值
  304. 304● let out : Array[Byte] = Array::make(n, b'\x00')
  305. 305 for i in 0..<n {
  306. 306● out[i] = if img.data[i].to_int() > threshold { b'\xFF' } else { b'\x00' }
  307. 307 }
  308. 308 @types.Image::{
  309. 309 width: w,
  310. 310 height: h,
  311. 311 channels: 1,
  312. 312● data: Bytes::from_array(out),
  313. 313 }
  314. 314}