image.process\feature\histogram.mbt

97.9% · 143 / 146 points · 400 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/// # 直方图 histogram
  3. 3///
  4. 4/// 图像处理算法模块
  5. 5/// 图像处理算法模块 Image processing algorithm module
  6. 6// 直方图操作(纯 MoonBit):均衡化 + 归一化
  7. 7
  8. 8///|
  9. 9/// 计算灰度直方图。返回 256 个 bin 的计数数组。
  10. 10/// 彩色图像先转灰度(BT.601)再计算。
  11. 11/// 优化:直接从 Bytes 读取,避免额外数组分配
  12. 12pub fn histogram(img : @types.Image) -> Array[Int32] raise @types.LoadError {
  13. 13 // 输入验证
  14. 14● if img.width <= 0 || img.height <= 0 {
  15. 15● raise @types.LoadError::DecodeFailed("histogram: 图像尺寸必须大于0")
  16. 16 }
  17. 17 if img.channels < 1 || img.channels > 4 {
  18. 18● raise @types.LoadError::DecodeFailed(
  19. 19 "histogram: 通道数必须在1-4之间",
  20. 20 )
  21. 21 }
  22. 22 let expected_size = img.width * img.height * img.channels
  23. 23● if img.data.length() != expected_size {
  24. 24● raise @types.LoadError::DecodeFailed(
  25. 25 "histogram: 数据大小不匹配,期望 " +
  26. 26● expected_size.to_string() +
  27. 27 ",实际 " +
  28. 28● img.data.length().to_string(),
  29. 29 )
  30. 30 }
  31. 31
  32. 32● let hist : Array[Int32] = Array::make(256, 0)
  33. 33 let n = img.width * img.height
  34. 34 let ch = img.channels
  35. 35 let data = img.data
  36. 36 for i in 0..<n {
  37. 37● let base = i * ch
  38. 38 let v = if ch == 1 {
  39. 39● data[base].to_int()
  40. 40 } else {
  41. 41● let r = data[base].to_int()
  42. 42● let g = data[base + 1].to_int()
  43. 43● let b = data[base + 2].to_int()
  44. 44 (r * 299 + g * 587 + b * 114) / 1000
  45. 45 }
  46. 46 hist[v] += 1
  47. 47 }
  48. 48 hist
  49. 49}
  50. 50
  51. 51///|
  52. 52/// 直方图均衡化。基于灰度直方图计算映射 LUT,应用到所有颜色通道。
  53. 53/// alpha 通道不变。
  54. 54pub fn histogram_equalize(
  55. 55 img : @types.Image,
  56. 56) -> @types.Image raise @types.LoadError {
  57. 57 // 输入验证
  58. 58● if img.width <= 0 || img.height <= 0 {
  59. 59● raise @types.LoadError::DecodeFailed(
  60. 60 "histogram_equalize: 图像尺寸必须大于0",
  61. 61 )
  62. 62 }
  63. 63 if img.channels < 1 || img.channels > 4 {
  64. 64● raise @types.LoadError::DecodeFailed(
  65. 65 "histogram_equalize: 通道数必须在1-4之间",
  66. 66 )
  67. 67 }
  68. 68 let expected_size = img.width * img.height * img.channels
  69. 69● if img.data.length() != expected_size {
  70. 70● raise @types.LoadError::DecodeFailed(
  71. 71 "histogram_equalize: 数据大小不匹配,期望 " +
  72. 72● expected_size.to_string() +
  73. 73 ",实际 " +
  74. 74● img.data.length().to_string(),
  75. 75 )
  76. 76 }
  77. 77
  78. 78● let hist = histogram(img)
  79. 79 let n = img.width * img.height
  80. 80 // 计算 CDF
  81. 81● let cdf : Array[Int32] = Array::make(256, 0)
  82. 82 let mut cum = 0
  83. 83 for i in 0..<256 {
  84. 84● cum += hist[i]
  85. 85 cdf[i] = cum
  86. 86 }
  87. 87 // 找到 CDF_min(第一个非零值)
  88. 88 let mut cdf_min = 0
  89. 89 for i in 0..<256 {
  90. 90● if cdf[i] > 0 {
  91. 91● cdf_min = cdf[i]
  92. 92 break
  93. 93 }
  94. 94 }
  95. 95 // 计算映射 LUT
  96. 96● let lut : Array[Byte] = Array::make(256, b'\x00')
  97. 97 let denom = n - cdf_min
  98. 98 if denom <= 0 {
  99. 99 // 所有像素相同,返回原图
  100. 100● return img
  101. 101 }
  102. 102 for i in 0..<256 {
  103. 103● let mapped = (cdf[i] - cdf_min) * 255 / denom
  104. 104● lut[i] = mapped.clamp(min=0, max=255).to_byte()
  105. 105 }
  106. 106 // 应用 LUT
  107. 107 let ch = img.channels
  108. 108● let color_ch = if ch >= 3 { 3 } else { ch }
  109. 109● let data_int : Array[Int32] = Array::make(n * ch, 0)
  110. 110 for i in 0..<(n * ch) {
  111. 111● data_int[i] = img.data[i].to_int()
  112. 112 }
  113. 113● let out : Array[Byte] = Array::make(n * ch, b'\x00')
  114. 114 for i in 0..<n {
  115. 115● for c in 0..<color_ch {
  116. 116● out[i * ch + c] = lut[data_int[i * ch + c]]
  117. 117 }
  118. 118 if ch == 4 {
  119. 119● out[i * ch + 3] = img.data[i * ch + 3]
  120. 120 }
  121. 121 }
  122. 122 @types.Image::{
  123. 123 width: img.width,
  124. 124 height: img.height,
  125. 125 channels: ch,
  126. 126● data: Bytes::from_array(out),
  127. 127 }
  128. 128}
  129. 129
  130. 130///|
  131. 131/// 直方图归一化(线性拉伸)。将像素值范围线性映射到 [0, 255]。
  132. 132/// alpha 通道不变。
  133. 133pub fn histogram_normalize(
  134. 134 img : @types.Image,
  135. 135) -> @types.Image raise @types.LoadError {
  136. 136 // 输入验证
  137. 137● if img.width <= 0 || img.height <= 0 {
  138. 138● raise @types.LoadError::DecodeFailed(
  139. 139 "histogram_normalize: 图像尺寸必须大于0",
  140. 140 )
  141. 141 }
  142. 142 if img.channels < 1 || img.channels > 4 {
  143. 143○ raise @types.LoadError::DecodeFailed(
  144. 144 "histogram_normalize: 通道数必须在1-4之间",
  145. 145 )
  146. 146 }
  147. 147 let expected_size = img.width * img.height * img.channels
  148. 148● if img.data.length() != expected_size {
  149. 149● raise @types.LoadError::DecodeFailed(
  150. 150 "histogram_normalize: 数据大小不匹配,期望 " +
  151. 151● expected_size.to_string() +
  152. 152 ",实际 " +
  153. 153● img.data.length().to_string(),
  154. 154 )
  155. 155 }
  156. 156
  157. 157 let ch = img.channels
  158. 158● let color_ch = if ch >= 3 { 3 } else { ch }
  159. 159 let n = img.width * img.height
  160. 160● let data_int : Array[Int32] = Array::make(n * ch, 0)
  161. 161 for i in 0..<(n * ch) {
  162. 162● data_int[i] = img.data[i].to_int()
  163. 163 }
  164. 164 // 找到颜色通道的最小值和最大值
  165. 165 let mut min_val = 255
  166. 166 let mut max_val = 0
  167. 167 for i in 0..<n {
  168. 168● for c in 0..<color_ch {
  169. 169● let v = data_int[i * ch + c]
  170. 170 if v < min_val {
  171. 171● min_val = v
  172. 172 }
  173. 173 if v > max_val {
  174. 174● max_val = v
  175. 175 }
  176. 176 }
  177. 177 }
  178. 178 let range = max_val - min_val
  179. 179 if range == 0 {
  180. 180● return img
  181. 181 }
  182. 182 // 应用线性拉伸
  183. 183● let out : Array[Byte] = Array::make(n * ch, b'\x00')
  184. 184 for i in 0..<n {
  185. 185● for c in 0..<color_ch {
  186. 186● let v = data_int[i * ch + c]
  187. 187 let scaled = (v - min_val) * 255 / range
  188. 188● out[i * ch + c] = scaled.clamp(min=0, max=255).to_byte()
  189. 189 }
  190. 190 if ch == 4 {
  191. 191● out[i * ch + 3] = img.data[i * ch + 3]
  192. 192 }
  193. 193 }
  194. 194 @types.Image::{
  195. 195 width: img.width,
  196. 196 height: img.height,
  197. 197 channels: ch,
  198. 198● data: Bytes::from_array(out),
  199. 199 }
  200. 200}
  201. 201
  202. 202///|
  203. 203/// 直方图比较方法
  204. 204pub(all) enum HistCompareMethod {
  205. 205 Correlation // 相关性
  206. 206 ChiSquare // 卡方
  207. 207 Bhattacharyya // 巴氏距离
  208. 208}
  209. 209
  210. 210///|
  211. 211/// 比较两个直方图的相似度。返回值越大表示越相似(Correlation/ChiSquare),
  212. 212/// 或距离越小越相似(Bhattacharyya)。
  213. 213pub fn compare_hist(
  214. 214 hist1 : Array[Int32],
  215. 215 hist2 : Array[Int32],
  216. 216 compare_method : HistCompareMethod,
  217. 217) -> Float raise @types.LoadError {
  218. 218 // 参数验证
  219. 219● if hist1.length() == 0 {
  220. 220● raise @types.LoadError::DecodeFailed(
  221. 221 "compare_hist: hist1数组不能为空",
  222. 222 )
  223. 223 }
  224. 224● if hist2.length() == 0 {
  225. 225● raise @types.LoadError::DecodeFailed(
  226. 226 "compare_hist: hist2数组不能为空",
  227. 227 )
  228. 228 }
  229. 229● if hist1.length() != hist2.length() {
  230. 230● raise @types.LoadError::DecodeFailed(
  231. 231 "compare_hist: hist1和hist2长度必须相同",
  232. 232 )
  233. 233 }
  234. 234
  235. 235● let n = hist1.length()
  236. 236● match compare_method {
  237. 237● Correlation => {
  238. 238 let mut sum1 = 0.0F
  239. 239 let mut sum2 = 0.0F
  240. 240 let mut sum12 = 0.0F
  241. 241 let mut sum1_sq = 0.0F
  242. 242 let mut sum2_sq = 0.0F
  243. 243 for i in 0..<n {
  244. 244● let h1 = Float::from_int(hist1[i])
  245. 245● let h2 = Float::from_int(hist2[i])
  246. 246 sum1 += h1
  247. 247 sum2 += h2
  248. 248 sum12 += h1 * h2
  249. 249 sum1_sq += h1 * h1
  250. 250 sum2_sq += h2 * h2
  251. 251 }
  252. 252● let nf = Float::from_int(n)
  253. 253 let num = nf * sum12 - sum1 * sum2
  254. 254● let den = ((nf * sum1_sq - sum1 * sum1) * (nf * sum2_sq - sum2 * sum2)).sqrt()
  255. 255 if den == 0.0F {
  256. 256● 0.0F
  257. 257 } else {
  258. 258● num / den
  259. 259 }
  260. 260 }
  261. 261● ChiSquare => {
  262. 262 let mut chi = 0.0F
  263. 263 for i in 0..<n {
  264. 264● let h1 = Float::from_int(hist1[i])
  265. 265● let h2 = Float::from_int(hist2[i])
  266. 266 let diff = h1 - h2
  267. 267 let sum = h1 + h2
  268. 268 if sum > 0.0F {
  269. 269● chi += diff * diff / sum
  270. 270 }
  271. 271 }
  272. 272 chi
  273. 273 }
  274. 274● Bhattacharyya => {
  275. 275 let mut bc = 0.0F
  276. 276 let mut s1 = 0.0F
  277. 277 let mut s2 = 0.0F
  278. 278 for i in 0..<n {
  279. 279● let h1 = Float::from_int(hist1[i])
  280. 280● let h2 = Float::from_int(hist2[i])
  281. 281● bc += (h1 * h2).sqrt()
  282. 282 s1 += h1
  283. 283 s2 += h2
  284. 284 }
  285. 285 if s1 > 0.0F && s2 > 0.0F {
  286. 286● bc / (s1 * s2).sqrt()
  287. 287 } else {
  288. 288● 0.0F
  289. 289 }
  290. 290 }
  291. 291 }
  292. 292}
  293. 293
  294. 294///|
  295. 295/// 直方图匹配(规定化)。将输入图像的直方图匹配到参考图像的直方图,
  296. 296/// 通过构建 LUT 实现灰度值映射。彩色图像对每个通道独立匹配。
  297. 297pub fn histogram_matching(
  298. 298 img : @types.Image,
  299. 299 reference : @types.Image,
  300. 300) -> @types.Image raise @types.LoadError {
  301. 301 // 输入验证
  302. 302● if img.width <= 0 || img.height <= 0 {
  303. 303● raise @types.LoadError::DecodeFailed(
  304. 304 "histogram_matching: 图像尺寸必须大于0",
  305. 305 )
  306. 306 }
  307. 307 if img.channels < 1 || img.channels > 4 {
  308. 308○ raise @types.LoadError::DecodeFailed(
  309. 309 "histogram_matching: 通道数必须在1-4之间",
  310. 310 )
  311. 311 }
  312. 312 let expected_size = img.width * img.height * img.channels
  313. 313● if img.data.length() != expected_size {
  314. 314● raise @types.LoadError::DecodeFailed(
  315. 315 "histogram_matching: 数据大小不匹配,期望 " +
  316. 316● expected_size.to_string() +
  317. 317 ",实际 " +
  318. 318● img.data.length().to_string(),
  319. 319 )
  320. 320 }
  321. 321 if reference.width <= 0 || reference.height <= 0 {
  322. 322● raise @types.LoadError::DecodeFailed(
  323. 323 "histogram_matching: 参考图像尺寸必须大于0",
  324. 324 )
  325. 325 }
  326. 326 if reference.channels < 1 || reference.channels > 4 {
  327. 327○ raise @types.LoadError::DecodeFailed(
  328. 328 "histogram_matching: 参考图像通道数必须在1-4之间",
  329. 329 )
  330. 330 }
  331. 331 let ref_expected_size = reference.width *
  332. 332 reference.height *
  333. 333 reference.channels
  334. 334● if reference.data.length() != ref_expected_size {
  335. 335● raise @types.LoadError::DecodeFailed(
  336. 336 "histogram_matching: 参考图像数据大小不匹配,期望 " +
  337. 337● ref_expected_size.to_string() +
  338. 338 ",实际 " +
  339. 339● reference.data.length().to_string(),
  340. 340 )
  341. 341 }
  342. 342
  343. 343 let ch = img.channels
  344. 344● let color_ch = if ch >= 3 { 3 } else { ch }
  345. 345 let n = img.width * img.height
  346. 346● let out : Array[Byte] = Array::make(n * ch, b'\x00')
  347. 347 for c in 0..<color_ch {
  348. 348● let hist_in : Array[Int32] = Array::make(256, 0)
  349. 349● let hist_ref : Array[Int32] = Array::make(256, 0)
  350. 350 for i in 0..<n {
  351. 351● hist_in[img.data[i * ch + c].to_int()] += 1
  352. 352 }
  353. 353 let n_ref = reference.width * reference.height
  354. 354 let ref_ch = reference.channels
  355. 355● let ref_color_ch = if ref_ch >= 3 { 3 } else { ref_ch }
  356. 356 if c < ref_color_ch {
  357. 357● for i in 0..<n_ref {
  358. 358● hist_ref[reference.data[i * ref_ch + c].to_int()] += 1
  359. 359 }
  360. 360 }
  361. 361● let cdf_in : Array[Float] = Array::make(256, 0.0F)
  362. 362● let cdf_ref : Array[Float] = Array::make(256, 0.0F)
  363. 363 let mut cum_in = 0
  364. 364 let mut cum_ref = 0
  365. 365 for i in 0..<256 {
  366. 366● cum_in += hist_in[i]
  367. 367● cdf_in[i] = Float::from_int(cum_in) / Float::from_int(n)
  368. 368 cum_ref += hist_ref[i]
  369. 369● cdf_ref[i] = Float::from_int(cum_ref) / Float::from_int(n_ref)
  370. 370 }
  371. 371● let lut : Array[Byte] = Array::make(256, b'\x00')
  372. 372 for i in 0..<256 {
  373. 373● let target = cdf_in[i]
  374. 374 let mut best_j = 0
  375. 375 let mut best_diff = 1.0F
  376. 376 for j in 0..<256 {
  377. 377● let diff = (cdf_ref[j] - target).abs()
  378. 378 if diff < best_diff {
  379. 379● best_diff = diff
  380. 380 best_j = j
  381. 381 }
  382. 382 }
  383. 383● lut[i] = best_j.to_byte()
  384. 384 }
  385. 385 for i in 0..<n {
  386. 386● out[i * ch + c] = lut[img.data[i * ch + c].to_int()]
  387. 387 }
  388. 388 }
  389. 389 if ch == 4 {
  390. 390● for i in 0..<n {
  391. 391● out[i * ch + 3] = img.data[i * ch + 3]
  392. 392 }
  393. 393 }
  394. 394 @types.Image::{
  395. 395 width: img.width,
  396. 396 height: img.height,
  397. 397 channels: ch,
  398. 398● data: Bytes::from_array(out),
  399. 399 }
  400. 400}