image.process\filter\bilateral_filter.mbt

86.5% · 96 / 111 points · 341 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/// # 双边滤波 bilateral filter
  3. 3///
  4. 4/// 图像处理算法模块
  5. 5/// 图像处理算法模块 Image processing algorithm module
  6. 6// 双边滤波(纯 MoonBit)
  7. 7
  8. 8///|
  9. 9/// 双边滤波。保边去噪滤波器,同时考虑空间距离和像素值差异。
  10. 10/// radius 为滤波半径,sigma_space 为空间高斯标准差,sigma_color 为值域高斯标准差。
  11. 11/// 仅处理灰度图(channels=1)或 RGB 图(channels=3/4),alpha 通道不变。
  12. 12pub fn bilateral_filter(
  13. 13 img : @types.Image,
  14. 14 radius : Int32,
  15. 15 sigma_space : Float,
  16. 16 sigma_color : Float,
  17. 17) -> @types.Image raise @types.LoadError {
  18. 18 // 输入验证
  19. 19● if img.width <= 0 || img.height <= 0 {
  20. 20● raise @types.LoadError::DecodeFailed(
  21. 21 "bilateral_filter: 图像尺寸必须大于0",
  22. 22 )
  23. 23 }
  24. 24 if img.channels != 1 && img.channels != 3 && img.channels != 4 {
  25. 25● raise @types.LoadError::DecodeFailed(
  26. 26 "bilateral_filter: 仅支持 channels=1/3/4",
  27. 27 )
  28. 28 }
  29. 29 let expected_size = img.width * img.height * img.channels
  30. 30● if img.data.length() != expected_size {
  31. 31● raise @types.LoadError::DecodeFailed(
  32. 32 "bilateral_filter: 数据大小不匹配,期望 " +
  33. 33● expected_size.to_string() +
  34. 34 ",实际 " +
  35. 35● img.data.length().to_string(),
  36. 36 )
  37. 37 }
  38. 38 if radius < 1 {
  39. 39● raise @types.LoadError::DecodeFailed("bilateral_filter: radius 必须 >= 1")
  40. 40 }
  41. 41 if sigma_space <= 0.0F {
  42. 42● raise @types.LoadError::DecodeFailed(
  43. 43 "bilateral_filter: sigma_space必须大于0",
  44. 44 )
  45. 45 }
  46. 46 if sigma_color <= 0.0F {
  47. 47○ raise @types.LoadError::DecodeFailed(
  48. 48 "bilateral_filter: sigma_color必须大于0",
  49. 49 )
  50. 50 }
  51. 51 let ch = img.channels
  52. 52● let color_ch = if ch >= 3 { 3 } else { 1 }
  53. 53 let w = img.width
  54. 54 let h = img.height
  55. 55 let n = w * h
  56. 56● let out : Array[Byte] = Array::make(n * ch, b'\x00')
  57. 57 let two_sps_sq = 2.0F * sigma_space * sigma_space
  58. 58 let two_spc_sq = 2.0F * sigma_color * sigma_color
  59. 59 // 预计算空间权重表(1D 扁平化,提升缓存局部性)
  60. 60 let sw_size = 2 * radius + 1
  61. 61● let spatial_weights : Array[Float] = Array::make(sw_size * sw_size, 0.0F)
  62. 62 for dy in -radius..<=radius {
  63. 63● for dx in -radius..<=radius {
  64. 64● let dist_sq = Float::from_int(dx * dx + dy * dy)
  65. 65● spatial_weights[(dy + radius) * sw_size + (dx + radius)] = @math.expf(
  66. 66 -dist_sq / two_sps_sq,
  67. 67 )
  68. 68 }
  69. 69 }
  70. 70 // 预计算像素 Float 数组,避免内层循环重复类型转换
  71. 71● let src : Array[Float] = Array::make(n * color_ch, 0.0F)
  72. 72 for i in 0..<n {
  73. 73● for c in 0..<color_ch {
  74. 74● src[i * color_ch + c] = Float::from_int(img.data[i * ch + c].to_int())
  75. 75 }
  76. 76 }
  77. 77 // 预计算 color exp 查找表:像素值差 0-255,避免内层循环调用 expf
  78. 78● let color_lut : Array[Float] = Array::make(256, 0.0F)
  79. 79 for d in 0..<256 {
  80. 80● let diff = Float::from_int(d)
  81. 81● color_lut[d] = @math.expf(-(diff * diff) / two_spc_sq)
  82. 82 }
  83. 83 // 分离内部/边界区域:内部区域所有邻居都在图像内,无需边界检查
  84. 84 let x_inner_start = radius
  85. 85 let x_inner_end = w - radius
  86. 86 let y_inner_start = radius
  87. 87 let y_inner_end = h - radius
  88. 88 if color_ch == 1 {
  89. 89 // color_ch=1 特化:消除内层通道循环和乘法
  90. 90● for y in 0..<h {
  91. 91● let y_inner = y >= y_inner_start && y < y_inner_end
  92. 92 for x in 0..<w {
  93. 93● let center_val = src[y * w + x]
  94. 94 let mut weight_sum = 0.0F
  95. 95 let mut value_sum = 0.0F
  96. 96 if y_inner && x >= x_inner_start && x < x_inner_end {
  97. 97● for dy in -radius..<=radius {
  98. 98● let row = (y + dy) * w + x
  99. 99 let sw_base = (dy + radius) * sw_size
  100. 100 for dx in -radius..<=radius {
  101. 101● let neighbor_val = src[row + dx]
  102. 102● let color_diff = (neighbor_val - center_val).to_int()
  103. 103 let abs_diff = if color_diff < 0 {
  104. 104● -color_diff
  105. 105 } else {
  106. 106● color_diff
  107. 107 }
  108. 108 let weight = spatial_weights[sw_base + dx + radius] *
  109. 109 color_lut[abs_diff]
  110. 110 value_sum += neighbor_val * weight
  111. 111 weight_sum += weight
  112. 112 }
  113. 113 }
  114. 114 } else {
  115. 115● for dy in -radius..<=radius {
  116. 116● let ny = y + dy
  117. 117 if ny < 0 || ny >= h {
  118. 118● continue
  119. 119 }
  120. 120 let sw_base = (dy + radius) * sw_size
  121. 121 for dx in -radius..<=radius {
  122. 122● let nx = x + dx
  123. 123 if nx < 0 || nx >= w {
  124. 124● continue
  125. 125 }
  126. 126 let neighbor_val = src[ny * w + nx]
  127. 127● let color_diff = (neighbor_val - center_val).to_int()
  128. 128 let abs_diff = if color_diff < 0 {
  129. 129● -color_diff
  130. 130 } else {
  131. 131● color_diff
  132. 132 }
  133. 133 let weight = spatial_weights[sw_base + dx + radius] *
  134. 134 color_lut[abs_diff]
  135. 135 value_sum += neighbor_val * weight
  136. 136 weight_sum += weight
  137. 137 }
  138. 138 }
  139. 139 }
  140. 140 let v = if weight_sum > 0.0F {
  141. 141● value_sum / weight_sum
  142. 142 } else {
  143. 143○ center_val
  144. 144 }
  145. 145 let clamped = if v < 0.0F {
  146. 146○ 0
  147. 147● } else if v > 255.0F {
  148. 148● 255
  149. 149 } else {
  150. 150● v.to_int()
  151. 151 }
  152. 152● out[y * w + x] = clamped.to_byte()
  153. 153 }
  154. 154 }
  155. 155 } else {
  156. 156● for c in 0..<color_ch {
  157. 157● for y in 0..<h {
  158. 158● let y_inner = y >= y_inner_start && y < y_inner_end
  159. 159 for x in 0..<w {
  160. 160● let center_idx = (y * w + x) * color_ch + c
  161. 161 let center_val = src[center_idx]
  162. 162 let mut weight_sum = 0.0F
  163. 163 let mut value_sum = 0.0F
  164. 164 if y_inner && x >= x_inner_start && x < x_inner_end {
  165. 165 // 内部区域:所有邻居都在图像内
  166. 166● for dy in -radius..<=radius {
  167. 167● let row = (y + dy) * w
  168. 168 let sw_base = (dy + radius) * sw_size
  169. 169 for dx in -radius..<=radius {
  170. 170● let neighbor_val = src[(row + x + dx) * color_ch + c]
  171. 171● let color_diff = (neighbor_val - center_val).to_int()
  172. 172 let abs_diff = if color_diff < 0 {
  173. 173● -color_diff
  174. 174 } else {
  175. 175● color_diff
  176. 176 }
  177. 177 let weight = spatial_weights[sw_base + dx + radius] *
  178. 178 color_lut[abs_diff]
  179. 179 value_sum += neighbor_val * weight
  180. 180 weight_sum += weight
  181. 181 }
  182. 182 }
  183. 183 } else {
  184. 184 // 边界区域:需要边界检查
  185. 185● for dy in -radius..<=radius {
  186. 186● let ny = y + dy
  187. 187 if ny < 0 || ny >= h {
  188. 188● continue
  189. 189 }
  190. 190 let sw_base = (dy + radius) * sw_size
  191. 191 for dx in -radius..<=radius {
  192. 192● let nx = x + dx
  193. 193 if nx < 0 || nx >= w {
  194. 194● continue
  195. 195 }
  196. 196 let neighbor_val = src[(ny * w + nx) * color_ch + c]
  197. 197● let color_diff = (neighbor_val - center_val).to_int()
  198. 198 let abs_diff = if color_diff < 0 {
  199. 199● -color_diff
  200. 200 } else {
  201. 201● color_diff
  202. 202 }
  203. 203 let weight = spatial_weights[sw_base + dx + radius] *
  204. 204 color_lut[abs_diff]
  205. 205 value_sum += neighbor_val * weight
  206. 206 weight_sum += weight
  207. 207 }
  208. 208 }
  209. 209 }
  210. 210 let v = if weight_sum > 0.0F {
  211. 211● value_sum / weight_sum
  212. 212 } else {
  213. 213○ center_val
  214. 214 }
  215. 215 let clamped = if v < 0.0F {
  216. 216○ 0
  217. 217● } else if v > 255.0F {
  218. 218● 255
  219. 219 } else {
  220. 220● v.to_int()
  221. 221 }
  222. 222● out[(y * w + x) * ch + c] = clamped.to_byte()
  223. 223 }
  224. 224 }
  225. 225 }
  226. 226 }
  227. 227 if ch == 4 {
  228. 228● for i in 0..<n {
  229. 229● out[i * 4 + 3] = img.data[i * 4 + 3]
  230. 230 }
  231. 231 }
  232. 232 @types.Image::{
  233. 233 width: w,
  234. 234 height: h,
  235. 235 channels: ch,
  236. 236● data: Bytes::from_array(out),
  237. 237 }
  238. 238}
  239. 239
  240. 240///|
  241. 241/// 快速双边滤波(使用降采样近似)。适用于大半径场景。
  242. 242/// downsample 为降采样倍数(1=不降采样,2=降采样到 1/2)。
  243. 243pub fn bilateral_filter_fast(
  244. 244 img : @types.Image,
  245. 245 radius : Int32,
  246. 246 sigma_space : Float,
  247. 247 sigma_color : Float,
  248. 248 downsample : Int32,
  249. 249) -> @types.Image raise @types.LoadError {
  250. 250 // 输入验证
  251. 251● if img.width <= 0 || img.height <= 0 {
  252. 252● raise @types.LoadError::DecodeFailed(
  253. 253 "bilateral_filter_fast: 图像尺寸必须大于0",
  254. 254 )
  255. 255 }
  256. 256 if img.channels != 1 && img.channels != 3 && img.channels != 4 {
  257. 257● raise @types.LoadError::DecodeFailed(
  258. 258 "bilateral_filter_fast: 仅支持 channels=1/3/4",
  259. 259 )
  260. 260 }
  261. 261 let expected_size = img.width * img.height * img.channels
  262. 262● if img.data.length() != expected_size {
  263. 263● raise @types.LoadError::DecodeFailed(
  264. 264 "bilateral_filter_fast: 数据大小不匹配,期望 " +
  265. 265● expected_size.to_string() +
  266. 266 ",实际 " +
  267. 267● img.data.length().to_string(),
  268. 268 )
  269. 269 }
  270. 270 if radius < 1 {
  271. 271● raise @types.LoadError::DecodeFailed(
  272. 272 "bilateral_filter_fast: radius 必须 >= 1",
  273. 273 )
  274. 274 }
  275. 275 if sigma_space <= 0.0F {
  276. 276● raise @types.LoadError::DecodeFailed(
  277. 277 "bilateral_filter_fast: sigma_space必须大于0",
  278. 278 )
  279. 279 }
  280. 280 if sigma_color <= 0.0F {
  281. 281○ raise @types.LoadError::DecodeFailed(
  282. 282 "bilateral_filter_fast: sigma_color必须大于0",
  283. 283 )
  284. 284 }
  285. 285 if downsample < 1 {
  286. 286○ raise @types.LoadError::DecodeFailed(
  287. 287 "bilateral_filter_fast: downsample必须 >= 1",
  288. 288 )
  289. 289 }
  290. 290
  291. 291 if downsample <= 1 {
  292. 292● return bilateral_filter(img, radius, sigma_space, sigma_color)
  293. 293 }
  294. 294 // 降采样
  295. 295 let mut small = img
  296. 296 for _ in 0..<downsample {
  297. 297● if small.width < 4 || small.height < 4 {
  298. 298○ break
  299. 299 }
  300. 300● small = @transform.pyr_down(small)
  301. 301 }
  302. 302 // 在小图上做双边滤波
  303. 303● let small_filtered = bilateral_filter(
  304. 304 small,
  305. 305● (radius / downsample).clamp(min=1, max=radius),
  306. 306 sigma_space,
  307. 307 sigma_color,
  308. 308 )
  309. 309 // 放大回原尺寸
  310. 310 let mut result = small_filtered
  311. 311 let target_w = img.width
  312. 312 let target_h = img.height
  313. 313 while result.width < target_w || result.height < target_h {
  314. 314● result = @transform.pyr_up(result)
  315. 315 }
  316. 316 // 裁剪到原尺寸
  317. 317 if result.width != target_w || result.height != target_h {
  318. 318○ crop_bilateral(result, target_w, target_h)
  319. 319 } else {
  320. 320● result
  321. 321 }
  322. 322}
  323. 323
  324. 324///|
  325. 325fn crop_bilateral(img : @types.Image, w : Int32, h : Int32) -> @types.Image {
  326. 326○ let ch = img.channels
  327. 327○ let out : Array[Byte] = Array::make(w * h * ch, b'\x00')
  328. 328 for y in 0..<h {
  329. 329○ for x in 0..<w {
  330. 330○ for c in 0..<ch {
  331. 331○ out[(y * w + x) * ch + c] = img.data[(y * img.width + x) * ch + c]
  332. 332 }
  333. 333 }
  334. 334 }
  335. 335 @types.Image::{
  336. 336 width: w,
  337. 337 height: h,
  338. 338 channels: ch,
  339. 339○ data: Bytes::from_array(out),
  340. 340 }
  341. 341}