image.process\color\adaptive_threshold.mbt

87.5% · 98 / 112 points · 320 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/// # 自适应阈值 adaptive threshold
  3. 3///
  4. 4/// 图像处理算法模块
  5. 5/// 图像处理算法模块 Image processing algorithm module
  6. 6// 自适应阈值(纯 MoonBit)
  7. 7
  8. 8///|
  9. 9/// 自适应阈值(均值法)。以每个像素周围 block_size×block_size 区域的均值减去 C 作为局部阈值。
  10. 10/// 仅处理灰度图(channels=1)或 RGB 图(channels=3/4),alpha 通道不变。
  11. 11pub fn adaptive_threshold_mean(
  12. 12 img : @types.Image,
  13. 13 block_size : Int32,
  14. 14 c : Int32,
  15. 15) -> @types.Image raise @types.LoadError {
  16. 16 // 输入验证
  17. 17● if img.width <= 0 || img.height <= 0 {
  18. 18● raise @types.LoadError::DecodeFailed(
  19. 19 "adaptive_threshold_mean: 图像尺寸必须大于0",
  20. 20 )
  21. 21 }
  22. 22 if img.channels != 1 && img.channels != 3 && img.channels != 4 {
  23. 23● raise @types.LoadError::DecodeFailed(
  24. 24 "adaptive_threshold_mean 仅支持 channels=1/3/4",
  25. 25 )
  26. 26 }
  27. 27 let expected_size = img.width * img.height * img.channels
  28. 28● if img.data.length() != expected_size {
  29. 29○ raise @types.LoadError::DecodeFailed(
  30. 30 "adaptive_threshold_mean: 数据大小不匹配,期望 " +
  31. 31○ expected_size.to_string() +
  32. 32 ",实际 " +
  33. 33○ img.data.length().to_string(),
  34. 34 )
  35. 35 }
  36. 36 if block_size < 3 || block_size % 2 == 0 {
  37. 37● raise @types.LoadError::DecodeFailed("block_size 必须为 >=3 的奇数")
  38. 38 }
  39. 39 let ch = img.channels
  40. 40● let color_ch = if ch >= 3 { 3 } else { 1 }
  41. 41 let w = img.width
  42. 42 let h = img.height
  43. 43 let n = w * h
  44. 44● let out : Array[Byte] = Array::make(n * ch, b'\x00')
  45. 45 let half = block_size / 2
  46. 46 // 预计算像素 Int 数组
  47. 47● let src : Array[Int32] = Array::make(n * ch, 0)
  48. 48 for i in 0..<(n * ch) {
  49. 49● src[i] = img.data[i].to_int()
  50. 50 }
  51. 51 // 内部区域 count 恒为 block_size²
  52. 52 let inner_count = block_size * block_size
  53. 53 for c_idx in 0..<color_ch {
  54. 54 // 内部区域:x in [half, w-half), y in [half, h-half)
  55. 55● for y in half..<(h - half) {
  56. 56● for x in half..<(w - half) {
  57. 57● let mut sum = 0
  58. 58 for dy in -half..<=half {
  59. 59● let row = (y + dy) * w
  60. 60 for dx in -half..<=half {
  61. 61● sum += src[(row + x + dx) * ch + c_idx]
  62. 62 }
  63. 63 }
  64. 64 let mean = sum / inner_count
  65. 65 let threshold = mean - c
  66. 66 let v = src[(y * w + x) * ch + c_idx]
  67. 67 out[(y * w + x) * ch + c_idx] = if v > threshold {
  68. 68● b'\xFF'
  69. 69 } else {
  70. 70● b'\x00'
  71. 71 }
  72. 72 }
  73. 73 }
  74. 74 // 边界区域
  75. 75 for y in 0..<h {
  76. 76● let y_inner = y >= half && y < h - half
  77. 77 for x in 0..<w {
  78. 78● if y_inner && x >= half && x < w - half {
  79. 79● continue
  80. 80 }
  81. 81 let mut sum = 0
  82. 82 let mut count = 0
  83. 83 for dy in -half..<=half {
  84. 84● for dx in -half..<=half {
  85. 85● let ny = y + dy
  86. 86 let nx = x + dx
  87. 87 if ny >= 0 && ny < h && nx >= 0 && nx < w {
  88. 88● sum += src[(ny * w + nx) * ch + c_idx]
  89. 89 count += 1
  90. 90 }
  91. 91 }
  92. 92 }
  93. 93◐ let mean = if count > 0 { sum / count } else { 0 }
  94. 94 let threshold = mean - c
  95. 95 let v = src[(y * w + x) * ch + c_idx]
  96. 96 out[(y * w + x) * ch + c_idx] = if v > threshold {
  97. 97● b'\xFF'
  98. 98 } else {
  99. 99● b'\x00'
  100. 100 }
  101. 101 }
  102. 102 }
  103. 103 }
  104. 104 if ch == 4 {
  105. 105● for i in 0..<n {
  106. 106● out[i * 4 + 3] = img.data[i * 4 + 3]
  107. 107 }
  108. 108 }
  109. 109 @types.Image::{
  110. 110 width: w,
  111. 111 height: h,
  112. 112 channels: ch,
  113. 113● data: Bytes::from_array(out),
  114. 114 }
  115. 115}
  116. 116
  117. 117///|
  118. 118/// 自适应阈值(高斯加权法)。以每个像素周围 block_size×block_size 区域的高斯加权均值减去 C 作为局部阈值。
  119. 119pub fn adaptive_threshold_gaussian(
  120. 120 img : @types.Image,
  121. 121 block_size : Int32,
  122. 122 c : Int32,
  123. 123) -> @types.Image raise @types.LoadError {
  124. 124 // 输入验证
  125. 125● if img.width <= 0 || img.height <= 0 {
  126. 126● raise @types.LoadError::DecodeFailed(
  127. 127 "adaptive_threshold_gaussian: 图像尺寸必须大于0",
  128. 128 )
  129. 129 }
  130. 130 if img.channels != 1 && img.channels != 3 && img.channels != 4 {
  131. 131● raise @types.LoadError::DecodeFailed(
  132. 132 "adaptive_threshold_gaussian 仅支持 channels=1/3/4",
  133. 133 )
  134. 134 }
  135. 135 let expected_size = img.width * img.height * img.channels
  136. 136● if img.data.length() != expected_size {
  137. 137○ raise @types.LoadError::DecodeFailed(
  138. 138 "adaptive_threshold_gaussian: 数据大小不匹配,期望 " +
  139. 139○ expected_size.to_string() +
  140. 140 ",实际 " +
  141. 141○ img.data.length().to_string(),
  142. 142 )
  143. 143 }
  144. 144 if block_size < 3 || block_size % 2 == 0 {
  145. 145● raise @types.LoadError::DecodeFailed("block_size 必须为 >=3 的奇数")
  146. 146 }
  147. 147 let ch = img.channels
  148. 148● let color_ch = if ch >= 3 { 3 } else { 1 }
  149. 149 let w = img.width
  150. 150 let h = img.height
  151. 151 let n = w * h
  152. 152● let out : Array[Byte] = Array::make(n * ch, b'\x00')
  153. 153 let half = block_size / 2
  154. 154● let sigma = Float::from_int(half) / 2.0F
  155. 155 let two_sigma_sq = 2.0F * sigma * sigma
  156. 156 // 预计算高斯权重(1D 扁平化)
  157. 157● let weights : Array[Float] = Array::make(block_size * block_size, 0.0F)
  158. 158 let mut total_weight = 0.0F
  159. 159 for dy in 0..<block_size {
  160. 160● for dx in 0..<block_size {
  161. 161● let fy = Float::from_int(dy - half)
  162. 162● let fx = Float::from_int(dx - half)
  163. 163● let wt = @math.expf(-(fx * fx + fy * fy) / two_sigma_sq)
  164. 164 weights[dy * block_size + dx] = wt
  165. 165 total_weight += wt
  166. 166 }
  167. 167 }
  168. 168 // 预计算像素 Float 数组
  169. 169● let src : Array[Float] = Array::make(n * ch, 0.0F)
  170. 170 for i in 0..<(n * ch) {
  171. 171● src[i] = Float::from_int(img.data[i].to_int())
  172. 172 }
  173. 173 for c_idx in 0..<color_ch {
  174. 174 // 内部区域:weight_sum 恒为 total_weight
  175. 175● for y in half..<(h - half) {
  176. 176● for x in half..<(w - half) {
  177. 177● let mut sum = 0.0F
  178. 178 for dy in 0..<block_size {
  179. 179● let row = (y + dy - half) * w
  180. 180 let wbase = dy * block_size
  181. 181 for dx in 0..<block_size {
  182. 182● sum += src[(row + x + dx - half) * ch + c_idx] * weights[wbase + dx]
  183. 183 }
  184. 184 }
  185. 185 let mean = sum / total_weight
  186. 186● let threshold = mean - Float::from_int(c)
  187. 187 let v = src[(y * w + x) * ch + c_idx]
  188. 188 out[(y * w + x) * ch + c_idx] = if v > threshold {
  189. 189● b'\xFF'
  190. 190 } else {
  191. 191● b'\x00'
  192. 192 }
  193. 193 }
  194. 194 }
  195. 195 // 边界区域
  196. 196 for y in 0..<h {
  197. 197● let y_inner = y >= half && y < h - half
  198. 198 for x in 0..<w {
  199. 199● if y_inner && x >= half && x < w - half {
  200. 200● continue
  201. 201 }
  202. 202 let mut sum = 0.0F
  203. 203 let mut weight_sum = 0.0F
  204. 204 for dy in -half..<=half {
  205. 205● for dx in -half..<=half {
  206. 206● let ny = y + dy
  207. 207 let nx = x + dx
  208. 208 if ny >= 0 && ny < h && nx >= 0 && nx < w {
  209. 209● let weight = weights[(dy + half) * block_size + (dx + half)]
  210. 210 sum += src[(ny * w + nx) * ch + c_idx] * weight
  211. 211 weight_sum += weight
  212. 212 }
  213. 213 }
  214. 214 }
  215. 215◐ let mean = if weight_sum > 0.0F { sum / weight_sum } else { 0.0F }
  216. 216● let threshold = mean - Float::from_int(c)
  217. 217 let v = src[(y * w + x) * ch + c_idx]
  218. 218 out[(y * w + x) * ch + c_idx] = if v > threshold {
  219. 219● b'\xFF'
  220. 220 } else {
  221. 221● b'\x00'
  222. 222 }
  223. 223 }
  224. 224 }
  225. 225 }
  226. 226 if ch == 4 {
  227. 227● for i in 0..<n {
  228. 228● out[i * 4 + 3] = img.data[i * 4 + 3]
  229. 229 }
  230. 230 }
  231. 231 @types.Image::{
  232. 232 width: w,
  233. 233 height: h,
  234. 234 channels: ch,
  235. 235● data: Bytes::from_array(out),
  236. 236 }
  237. 237}
  238. 238
  239. 239///|
  240. 240/// Otsu 大津法自动阈值。自动计算最佳全局阈值并二值化。
  241. 241pub fn threshold_otsu(
  242. 242 img : @types.Image,
  243. 243) -> @types.Image raise @types.LoadError {
  244. 244 // 输入验证
  245. 245● if img.width <= 0 || img.height <= 0 {
  246. 246● raise @types.LoadError::DecodeFailed(
  247. 247 "threshold_otsu: 图像尺寸必须大于0",
  248. 248 )
  249. 249 }
  250. 250 if img.channels != 1 && img.channels != 3 && img.channels != 4 {
  251. 251● raise @types.LoadError::DecodeFailed(
  252. 252 "threshold_otsu 仅支持 channels=1/3/4",
  253. 253 )
  254. 254 }
  255. 255 let expected_size = img.width * img.height * img.channels
  256. 256● if img.data.length() != expected_size {
  257. 257○ raise @types.LoadError::DecodeFailed(
  258. 258 "threshold_otsu: 数据大小不匹配,期望 " +
  259. 259○ expected_size.to_string() +
  260. 260 ",实际 " +
  261. 261○ img.data.length().to_string(),
  262. 262 )
  263. 263 }
  264. 264 let ch = img.channels
  265. 265● let color_ch = if ch >= 3 { 3 } else { 1 }
  266. 266 let w = img.width
  267. 267 let h = img.height
  268. 268 let n = w * h
  269. 269● let out : Array[Byte] = Array::make(n * ch, b'\x00')
  270. 270 for c_idx in 0..<color_ch {
  271. 271● let hist : Array[Int32] = Array::make(256, 0)
  272. 272 for i in 0..<n {
  273. 273● hist[img.data[i * ch + c_idx].to_int()] += 1
  274. 274 }
  275. 275 let mut total = 0
  276. 276 let mut sum = 0
  277. 277 for t in 0..<256 {
  278. 278● total += hist[t]
  279. 279 sum += t * hist[t]
  280. 280 }
  281. 281 let mut best_t = 0
  282. 282 let mut best_var = -1.0F
  283. 283 let mut w0 = 0
  284. 284 let mut sum0 = 0
  285. 285 for t in 0..<256 {
  286. 286● w0 += hist[t]
  287. 287 sum0 += t * hist[t]
  288. 288 if w0 == 0 || w0 == total {
  289. 289● continue
  290. 290 }
  291. 291 let w1 = total - w0
  292. 292 let sum1 = sum - sum0
  293. 293● let mean0 = Float::from_int(sum0) / Float::from_int(w0)
  294. 294● let mean1 = Float::from_int(sum1) / Float::from_int(w1)
  295. 295● let var_between = Float::from_int(w0) *
  296. 296● Float::from_int(w1) *
  297. 297 (mean0 - mean1) *
  298. 298 (mean0 - mean1)
  299. 299 if var_between > best_var {
  300. 300● best_var = var_between
  301. 301 best_t = t
  302. 302 }
  303. 303 }
  304. 304 for i in 0..<n {
  305. 305● let v = img.data[i * ch + c_idx].to_int()
  306. 306● out[i * ch + c_idx] = if v > best_t { b'\xFF' } else { b'\x00' }
  307. 307 }
  308. 308 }
  309. 309 if ch == 4 {
  310. 310● for i in 0..<n {
  311. 311● out[i * 4 + 3] = img.data[i * 4 + 3]
  312. 312 }
  313. 313 }
  314. 314 @types.Image::{
  315. 315 width: w,
  316. 316 height: h,
  317. 317 channels: ch,
  318. 318● data: Bytes::from_array(out),
  319. 319 }
  320. 320}