image.process\color\retinex.mbt

88.2% · 142 / 161 points · 385 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/// # Retinex retinex
  3. 3///
  4. 4/// 图像处理算法模块
  5. 5/// 图像处理算法模块 Image processing algorithm module
  6. 6// 多尺度 Retinex(纯 MoonBit)
  7. 7
  8. 8///|
  9. 9/// Float 自然对数辅助函数
  10. 10fn logf(x : Float) -> Float {
  11. 11● Float::from_double(@math.log2(x.to_double()) * 0.6931471805599453)
  12. 12}
  13. 13
  14. 14///|
  15. 15/// 单尺度 Retinex(SSR)。
  16. 16/// 对每个像素计算 log(I) - log(I * G_sigma),
  17. 17/// 其中 G_sigma 为高斯滤波器。
  18. 18/// 适用于灰度图(channels=1)或 RGB/RGBA 图(channels=3/4)。
  19. 19/// sigma 为高斯标准差,gain 为增益,offset 为偏移。
  20. 20pub fn ssr(
  21. 21 img : @types.Image,
  22. 22 sigma~ : Float = 80.0F,
  23. 23 gain~ : Float = 1.0F,
  24. 24 offset~ : Float = 0.0F,
  25. 25) -> @types.Image raise @types.LoadError {
  26. 26 // 输入验证
  27. 27● if img.width == 0 || img.height == 0 {
  28. 28● return img
  29. 29 }
  30. 30 if img.width < 0 || img.height < 0 {
  31. 31○ raise @types.LoadError::DecodeFailed("ssr: 图像尺寸不能为负")
  32. 32 }
  33. 33 if img.channels != 1 && img.channels != 3 && img.channels != 4 {
  34. 34● raise @types.LoadError::DecodeFailed("ssr 仅支持 channels=1/3/4")
  35. 35 }
  36. 36 let expected_size = img.width * img.height * img.channels
  37. 37● if img.data.length() != expected_size {
  38. 38● raise @types.LoadError::DecodeFailed(
  39. 39 "ssr: 数据大小不匹配,期望 " +
  40. 40● expected_size.to_string() +
  41. 41 ",实际 " +
  42. 42● img.data.length().to_string(),
  43. 43 )
  44. 44 }
  45. 45 if sigma <= 0.0F {
  46. 46● raise @types.LoadError::DecodeFailed("sigma 必须 > 0")
  47. 47 }
  48. 48 let ch = img.channels
  49. 49 let w = img.width
  50. 50 let h = img.height
  51. 51 let n = w * h
  52. 52 if n == 0 {
  53. 53○ return img
  54. 54 }
  55. 55● let out : Array[Byte] = Array::make(n * ch, b'\x00')
  56. 56 for c in 0..<ch {
  57. 57● if ch == 4 && c == 3 {
  58. 58● for i in 0..<n {
  59. 59● out[i * ch + 3] = img.data[i * ch + 3]
  60. 60 }
  61. 61 continue
  62. 62 }
  63. 63● let channel : Array[Float] = Array::make(n, 0.0F)
  64. 64 for i in 0..<n {
  65. 65● let v = img.data[i * ch + c].to_int()
  66. 66● channel[i] = Float::from_int(if v == 0 { 1 } else { v })
  67. 67 }
  68. 68● let blurred = gaussian_blur_channel(channel, w, h, sigma)
  69. 69 for i in 0..<n {
  70. 70● let log_i = logf(channel[i])
  71. 71◐ let log_b = logf(if blurred[i] > 0.0F { blurred[i] } else { 1.0F })
  72. 72 let retinex = (log_i - log_b) * gain + offset
  73. 73● let val = (retinex * 30.0F + 128.0F).to_int()
  74. 74● out[i * ch + c] = val.clamp(min=0, max=255).to_byte()
  75. 75 }
  76. 76 }
  77. 77 @types.Image::{
  78. 78 width: w,
  79. 79 height: h,
  80. 80 channels: ch,
  81. 81● data: Bytes::from_array(out),
  82. 82 }
  83. 83}
  84. 84
  85. 85///|
  86. 86/// 多尺度 Retinex(MSR)。
  87. 87/// 对多个不同 sigma 的 SSR 结果取平均。
  88. 88/// 适用于灰度图(channels=1)或 RGB/RGBA 图(channels=3/4)。
  89. 89/// sigmas 为高斯标准差数组(默认 [15, 80, 250])。
  90. 90/// gain 为增益,offset 为偏移。
  91. 91pub fn msr(
  92. 92 img : @types.Image,
  93. 93 sigmas~ : Array[Float] = [15.0F, 80.0F, 250.0F],
  94. 94 gain~ : Float = 1.0F,
  95. 95 offset~ : Float = 0.0F,
  96. 96) -> @types.Image raise @types.LoadError {
  97. 97 // 输入验证
  98. 98● if img.width == 0 || img.height == 0 {
  99. 99● return img
  100. 100 }
  101. 101 if img.width < 0 || img.height < 0 {
  102. 102○ raise @types.LoadError::DecodeFailed("msr: 图像尺寸不能为负")
  103. 103 }
  104. 104 if img.channels != 1 && img.channels != 3 && img.channels != 4 {
  105. 105● raise @types.LoadError::DecodeFailed("msr 仅支持 channels=1/3/4")
  106. 106 }
  107. 107 let expected_size = img.width * img.height * img.channels
  108. 108● if img.data.length() != expected_size {
  109. 109● raise @types.LoadError::DecodeFailed(
  110. 110 "msr: 数据大小不匹配,期望 " +
  111. 111● expected_size.to_string() +
  112. 112 ",实际 " +
  113. 113● img.data.length().to_string(),
  114. 114 )
  115. 115 }
  116. 116● if sigmas.length() == 0 {
  117. 117● raise @types.LoadError::DecodeFailed("sigmas 不能为空")
  118. 118 }
  119. 119 for s in sigmas {
  120. 120● if s <= 0.0F {
  121. 121● raise @types.LoadError::DecodeFailed("sigma 必须 > 0")
  122. 122 }
  123. 123 }
  124. 124 let ch = img.channels
  125. 125 let w = img.width
  126. 126 let h = img.height
  127. 127 let n = w * h
  128. 128 if n == 0 {
  129. 129○ return img
  130. 130 }
  131. 131● let out : Array[Byte] = Array::make(n * ch, b'\x00')
  132. 132● let num_scales = sigmas.length()
  133. 133 for c in 0..<ch {
  134. 134● if ch == 4 && c == 3 {
  135. 135● for i in 0..<n {
  136. 136● out[i * ch + 3] = img.data[i * ch + 3]
  137. 137 }
  138. 138 continue
  139. 139 }
  140. 140● let channel : Array[Float] = Array::make(n, 0.0F)
  141. 141 for i in 0..<n {
  142. 142● let v = img.data[i * ch + c].to_int()
  143. 143● channel[i] = Float::from_int(if v == 0 { 1 } else { v })
  144. 144 }
  145. 145 // 预计算 log(channel[i]),避免在每个 sigma 循环中重复计算
  146. 146● let log_channel : Array[Float] = Array::make(n, 0.0F)
  147. 147 for i in 0..<n {
  148. 148● log_channel[i] = logf(channel[i])
  149. 149 }
  150. 150● let retinex_sum : Array[Float] = Array::make(n, 0.0F)
  151. 151 for sigma in sigmas {
  152. 152● let blurred = gaussian_blur_channel(channel, w, h, sigma)
  153. 153 for i in 0..<n {
  154. 154◐ let log_b = logf(if blurred[i] > 0.0F { blurred[i] } else { 1.0F })
  155. 155 retinex_sum[i] += log_channel[i] - log_b
  156. 156 }
  157. 157 }
  158. 158● let inv_scales = gain / Float::from_int(num_scales)
  159. 159 for i in 0..<n {
  160. 160● let retinex = retinex_sum[i] * inv_scales + offset
  161. 161● let val = (retinex * 30.0F + 128.0F).to_int()
  162. 162● out[i * ch + c] = val.clamp(min=0, max=255).to_byte()
  163. 163 }
  164. 164 }
  165. 165 @types.Image::{
  166. 166 width: w,
  167. 167 height: h,
  168. 168 channels: ch,
  169. 169● data: Bytes::from_array(out),
  170. 170 }
  171. 171}
  172. 172
  173. 173///|
  174. 174/// 带颜色恢复的多尺度 Retinex(MSRCR)。
  175. 175/// 在 MSR 基础上恢复颜色信息。
  176. 176/// 适用于 RGB/RGBA 图(channels=3/4)。
  177. 177pub fn msrcr(
  178. 178 img : @types.Image,
  179. 179 sigmas~ : Array[Float] = [15.0F, 80.0F, 250.0F],
  180. 180 gain~ : Float = 1.0F,
  181. 181 offset~ : Float = 0.0F,
  182. 182 alpha~ : Float = 125.0F,
  183. 183 beta~ : Float = 46.0F,
  184. 184) -> @types.Image raise @types.LoadError {
  185. 185● if img.channels != 3 && img.channels != 4 {
  186. 186● raise @types.LoadError::DecodeFailed("msrcr 需要 RGB/RGBA 图像")
  187. 187 }
  188. 188● if sigmas.length() == 0 {
  189. 189● raise @types.LoadError::DecodeFailed("sigmas 不能为空")
  190. 190 }
  191. 191 let ch = img.channels
  192. 192 let w = img.width
  193. 193 let h = img.height
  194. 194 let n = w * h
  195. 195 if n == 0 {
  196. 196● return img
  197. 197 }
  198. 198● let out : Array[Byte] = Array::make(n * ch, b'\x00')
  199. 199● let num_scales = sigmas.length()
  200. 200 // 提取各通道
  201. 201 let channels : Array[Array[Float]] = [
  202. 202● Array::make(n, 0.0F),
  203. 203● Array::make(n, 0.0F),
  204. 204● Array::make(n, 0.0F),
  205. 205 ]
  206. 206 for c in 0..<3 {
  207. 207● for i in 0..<n {
  208. 208● let v = img.data[i * ch + c].to_int()
  209. 209◐ channels[c][i] = Float::from_int(if v == 0 { 1 } else { v })
  210. 210 }
  211. 211 }
  212. 212 // 计算各通道 MSR
  213. 213 let msr_results : Array[Array[Float]] = [
  214. 214● Array::make(n, 0.0F),
  215. 215● Array::make(n, 0.0F),
  216. 216● Array::make(n, 0.0F),
  217. 217 ]
  218. 218 for c in 0..<3 {
  219. 219 // 预计算 log(channel[i])
  220. 220● let log_channel : Array[Float] = Array::make(n, 0.0F)
  221. 221 for i in 0..<n {
  222. 222● log_channel[i] = logf(channels[c][i])
  223. 223 }
  224. 224● let retinex_sum : Array[Float] = Array::make(n, 0.0F)
  225. 225 for sigma in sigmas {
  226. 226● let blurred = gaussian_blur_channel(channels[c], w, h, sigma)
  227. 227 for i in 0..<n {
  228. 228◐ let log_b = logf(if blurred[i] > 0.0F { blurred[i] } else { 1.0F })
  229. 229 retinex_sum[i] += log_channel[i] - log_b
  230. 230 }
  231. 231 }
  232. 232● let inv_scales = 1.0F / Float::from_int(num_scales)
  233. 233 for i in 0..<n {
  234. 234● msr_results[c][i] = retinex_sum[i] * inv_scales
  235. 235 }
  236. 236 }
  237. 237 // 颜色恢复因子
  238. 238 for i in 0..<n {
  239. 239● let sum = channels[0][i] + channels[1][i] + channels[2][i]
  240. 240 for c in 0..<3 {
  241. 241● let crf = logf(alpha * channels[c][i] / (sum + 1.0F)) * beta
  242. 242 let val = msr_results[c][i] * gain + offset + crf
  243. 243● let mapped = (val * 30.0F + 128.0F).to_int()
  244. 244● out[i * ch + c] = mapped.clamp(min=0, max=255).to_byte()
  245. 245 }
  246. 246 if ch == 4 {
  247. 247● out[i * ch + 3] = img.data[i * ch + 3]
  248. 248 }
  249. 249 }
  250. 250 @types.Image::{
  251. 251 width: w,
  252. 252 height: h,
  253. 253 channels: ch,
  254. 254● data: Bytes::from_array(out),
  255. 255 }
  256. 256}
  257. 257
  258. 258///|
  259. 259/// 对单通道进行高斯模糊
  260. 260fn gaussian_blur_channel(
  261. 261 channel : Array[Float],
  262. 262 w : Int32,
  263. 263 h : Int32,
  264. 264 sigma : Float,
  265. 265) -> Array[Float] {
  266. 266● let n = w * h
  267. 267● let out : Array[Float] = Array::make(n, 0.0F)
  268. 268● let radius = (Float::from_int(3) * sigma).to_int()
  269. 269◐ let radius = if radius < 1 { 1 } else { radius }
  270. 270 let kernel_size = 2 * radius + 1
  271. 271● let kernel : Array[Float] = Array::make(kernel_size, 0.0F)
  272. 272 let two_sigma_sq = 2.0F * sigma * sigma
  273. 273 let mut kernel_sum = 0.0F
  274. 274 for i in 0..<kernel_size {
  275. 275● let x = Float::from_int(i - radius)
  276. 276● kernel[i] = @math.expf(-(x * x) / two_sigma_sq)
  277. 277 kernel_sum += kernel[i]
  278. 278 }
  279. 279 for i in 0..<kernel_size {
  280. 280● kernel[i] = kernel[i] / kernel_sum
  281. 281 }
  282. 282 // kernel prefix sum,用于大 radius 时 O(w) 替代 O(kernel_size)
  283. 283● let k_prefix : Array[Float] = Array::make(kernel_size + 1, 0.0F)
  284. 284 for i in 0..<kernel_size {
  285. 285● k_prefix[i + 1] = k_prefix[i] + kernel[i]
  286. 286 }
  287. 287 let total_k = k_prefix[kernel_size]
  288. 288 // 水平模糊
  289. 289● let temp : Array[Float] = Array::make(n, 0.0F)
  290. 290 if radius >= w {
  291. 291 // 大 radius:所有像素都是边界,用 prefix sum 将 O(kernel_size) 降为 O(w)
  292. 292● for y in 0..<h {
  293. 293● let row_base = y * w
  294. 294 let c0 = channel[row_base]
  295. 295 let cw1 = channel[row_base + w - 1]
  296. 296 for x in 0..<w {
  297. 297● let left_end = radius - x
  298. 298 let right_start = left_end + w
  299. 299◐ let mid_start = if left_end > 0 { left_end } else { 0 }
  300. 300 let mid_end = if right_start < kernel_size {
  301. 301● right_start
  302. 302 } else {
  303. 303○ kernel_size
  304. 304 }
  305. 305 let mut sum = c0 * k_prefix[mid_start] +
  306. 306 cw1 * (total_k - k_prefix[mid_end])
  307. 307 for k in mid_start..<mid_end {
  308. 308● sum += channel[row_base + k - left_end] * kernel[k]
  309. 309 }
  310. 310 temp[row_base + x] = sum
  311. 311 }
  312. 312 }
  313. 313 } else {
  314. 314 // 正常情况:分离内部/边界区域
  315. 315● for y in 0..<h {
  316. 316● let row_base = y * w
  317. 317 for x in radius..<(w - radius) {
  318. 318○ let mut sum = 0.0F
  319. 319 let base = row_base + x - radius
  320. 320 for k in 0..<kernel_size {
  321. 321○ sum += channel[base + k] * kernel[k]
  322. 322 }
  323. 323 temp[row_base + x] = sum
  324. 324 }
  325. 325 for x in 0..<w {
  326. 326● if x >= radius && x < w - radius {
  327. 327○ continue
  328. 328 }
  329. 329 let mut sum = 0.0F
  330. 330 for k in -radius..<=radius {
  331. 331● let px = (x + k).clamp(min=0, max=w - 1)
  332. 332 sum += channel[row_base + px] * kernel[k + radius]
  333. 333 }
  334. 334 temp[row_base + x] = sum
  335. 335 }
  336. 336 }
  337. 337 }
  338. 338 // 垂直模糊
  339. 339 if radius >= h {
  340. 340 // 大 radius:用 prefix sum 优化
  341. 341● for x in 0..<w {
  342. 342● let c0 = temp[x]
  343. 343 let ch1 = temp[(h - 1) * w + x]
  344. 344 for y in 0..<h {
  345. 345● let left_end = radius - y
  346. 346 let right_start = left_end + h
  347. 347◐ let mid_start = if left_end > 0 { left_end } else { 0 }
  348. 348 let mid_end = if right_start < kernel_size {
  349. 349● right_start
  350. 350 } else {
  351. 351○ kernel_size
  352. 352 }
  353. 353 let mut sum = c0 * k_prefix[mid_start] +
  354. 354 ch1 * (total_k - k_prefix[mid_end])
  355. 355 for k in mid_start..<mid_end {
  356. 356● sum += temp[(k - left_end) * w + x] * kernel[k]
  357. 357 }
  358. 358 out[y * w + x] = sum
  359. 359 }
  360. 360 }
  361. 361 } else {
  362. 362● for x in 0..<w {
  363. 363● for y in radius..<(h - radius) {
  364. 364○ let mut sum = 0.0F
  365. 365 let base = (y - radius) * w + x
  366. 366 for k in 0..<kernel_size {
  367. 367○ sum += temp[base + k * w] * kernel[k]
  368. 368 }
  369. 369 out[y * w + x] = sum
  370. 370 }
  371. 371 for y in 0..<h {
  372. 372● if y >= radius && y < h - radius {
  373. 373○ continue
  374. 374 }
  375. 375 let mut sum = 0.0F
  376. 376 for k in -radius..<=radius {
  377. 377● let py = (y + k).clamp(min=0, max=h - 1)
  378. 378 sum += temp[py * w + x] * kernel[k + radius]
  379. 379 }
  380. 380 out[y * w + x] = sum
  381. 381 }
  382. 382 }
  383. 383 }
  384. 384 out
  385. 385}