image.process\frequency\fft.mbt

96.3% · 105 / 109 points · 331 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/// # 快速傅里叶变换 fft
  3. 3///
  4. 4/// 图像处理算法模块
  5. 5/// 图像处理算法模块 Image processing algorithm module
  6. 6// FFT 频域变换(纯 MoonBit)
  7. 7
  8. 8///|
  9. 9/// 复数
  10. 10pub struct Complex {
  11. 11 re : Float
  12. 12 im : Float
  13. 13}
  14. 14
  15. 15///|
  16. 16/// 2D FFT 结果
  17. 17pub struct FFTResult {
  18. 18 width : Int32
  19. 19 height : Int32
  20. 20 data : Array[Complex]
  21. 21}
  22. 22
  23. 23///|
  24. 24/// 2D 快速傅里叶变换。将图像变换到频域。
  25. 25/// 图像尺寸自动补零到 2 的幂次方。
  26. 26/// 对灰度图(channels=1)或 RGB 图(channels=3/4)每通道独立变换,返回各通道结果。
  27. 27pub fn fft_2d(img : @types.Image) -> Array[FFTResult] raise @types.LoadError {
  28. 28● if img.channels != 1 && img.channels != 3 && img.channels != 4 {
  29. 29● raise @types.LoadError::DecodeFailed("fft_2d 仅支持 channels=1/3/4")
  30. 30 }
  31. 31 let ch = img.channels
  32. 32● let color_ch = if ch >= 3 { 3 } else { 1 }
  33. 33 let results : Array[FFTResult] = []
  34. 34 for c in 0..<color_ch {
  35. 35● results.push(fft_2d_channel(img, c, ch))
  36. 36 }
  37. 37 results
  38. 38}
  39. 39
  40. 40///|
  41. 41fn fft_2d_channel(img : @types.Image, channel : Int32, ch : Int32) -> FFTResult {
  42. 42● let w = img.width
  43. 43 let h = img.height
  44. 44● let pw = next_pow2(w)
  45. 45● let ph = next_pow2(h)
  46. 46 let n = pw * ph
  47. 47 // 分离实虚部数组,减少 Complex 对象分配,提升缓存局部性
  48. 48● let re : Array[Float] = Array::make(n, 0.0F)
  49. 49● let im : Array[Float] = Array::make(n, 0.0F)
  50. 50 for y in 0..<h {
  51. 51● for x in 0..<w {
  52. 52● re[y * pw + x] = Float::from_int(
  53. 53● img.data[(y * w + x) * ch + channel].to_int(),
  54. 54 )
  55. 55 }
  56. 56 }
  57. 57 // 行变换
  58. 58● let row_re : Array[Float] = Array::make(pw, 0.0F)
  59. 59● let row_im : Array[Float] = Array::make(pw, 0.0F)
  60. 60 for y in 0..<ph {
  61. 61● let base = y * pw
  62. 62 for x in 0..<pw {
  63. 63● row_re[x] = re[base + x]
  64. 64 row_im[x] = im[base + x]
  65. 65 }
  66. 66● fft_1d_split(row_re, row_im, false)
  67. 67 for x in 0..<pw {
  68. 68● re[base + x] = row_re[x]
  69. 69 im[base + x] = row_im[x]
  70. 70 }
  71. 71 }
  72. 72 // 列变换
  73. 73● let col_re : Array[Float] = Array::make(ph, 0.0F)
  74. 74● let col_im : Array[Float] = Array::make(ph, 0.0F)
  75. 75 for x in 0..<pw {
  76. 76● for y in 0..<ph {
  77. 77● col_re[y] = re[y * pw + x]
  78. 78 col_im[y] = im[y * pw + x]
  79. 79 }
  80. 80● fft_1d_split(col_re, col_im, false)
  81. 81 for y in 0..<ph {
  82. 82● re[y * pw + x] = col_re[y]
  83. 83 im[y * pw + x] = col_im[y]
  84. 84 }
  85. 85 }
  86. 86 // 转换回 Array[Complex]
  87. 87● let data : Array[Complex] = Array::make(n, Complex::{ re: 0.0F, im: 0.0F, })
  88. 88 for i in 0..<n {
  89. 89● data[i] = Complex::{ re: re[i], im: im[i], }
  90. 90 }
  91. 91 FFTResult::{ width: pw, height: ph, data, }
  92. 92}
  93. 93
  94. 94///|
  95. 95/// 2D 逆快速傅里叶变换。将频域结果变换回空域灰度图。
  96. 96pub fn ifft_2d(fft : FFTResult) -> @types.Image {
  97. 97● let pw = fft.width
  98. 98 let ph = fft.height
  99. 99 let n = pw * ph
  100. 100 // 分离实虚部数组
  101. 101● let re : Array[Float] = Array::make(n, 0.0F)
  102. 102● let im : Array[Float] = Array::make(n, 0.0F)
  103. 103 for i in 0..<n {
  104. 104● re[i] = fft.data[i].re
  105. 105 im[i] = fft.data[i].im
  106. 106 }
  107. 107 // 行变换
  108. 108● let row_re : Array[Float] = Array::make(pw, 0.0F)
  109. 109● let row_im : Array[Float] = Array::make(pw, 0.0F)
  110. 110 for y in 0..<ph {
  111. 111● let base = y * pw
  112. 112 for x in 0..<pw {
  113. 113● row_re[x] = re[base + x]
  114. 114 row_im[x] = im[base + x]
  115. 115 }
  116. 116● fft_1d_split(row_re, row_im, true)
  117. 117 for x in 0..<pw {
  118. 118● re[base + x] = row_re[x]
  119. 119 im[base + x] = row_im[x]
  120. 120 }
  121. 121 }
  122. 122 // 列变换
  123. 123● let col_re : Array[Float] = Array::make(ph, 0.0F)
  124. 124● let col_im : Array[Float] = Array::make(ph, 0.0F)
  125. 125 for x in 0..<pw {
  126. 126● for y in 0..<ph {
  127. 127● col_re[y] = re[y * pw + x]
  128. 128 col_im[y] = im[y * pw + x]
  129. 129 }
  130. 130● fft_1d_split(col_re, col_im, true)
  131. 131 for y in 0..<ph {
  132. 132● re[y * pw + x] = col_re[y]
  133. 133 im[y * pw + x] = col_im[y]
  134. 134 }
  135. 135 }
  136. 136● let norm = Float::from_int(n)
  137. 137● let out : Array[Byte] = Array::make(n, b'\x00')
  138. 138 for i in 0..<n {
  139. 139● let v = re[i] / norm
  140. 140 let clamped = if v < 0.0F {
  141. 141● 0
  142. 142● } else if v > 255.0F {
  143. 143○ 255
  144. 144 } else {
  145. 145● v.to_int()
  146. 146 }
  147. 147● out[i] = clamped.to_byte()
  148. 148 }
  149. 149 @types.Image::{
  150. 150 width: pw,
  151. 151 height: ph,
  152. 152 channels: 1,
  153. 153● data: Bytes::from_array(out),
  154. 154 }
  155. 155}
  156. 156
  157. 157///|
  158. 158/// 计算 FFT 幅度谱(用于可视化)。
  159. 159/// log_scale=true 时使用对数缩放 log(1+magnitude)。
  160. 160pub fn fft_magnitude(fft : FFTResult, log_scale : Bool) -> @types.Image {
  161. 161● let n = fft.width * fft.height
  162. 162● let out : Array[Byte] = Array::make(n, b'\x00')
  163. 163 let mut max_mag = 0.0F
  164. 164● let mags : Array[Float] = Array::make(n, 0.0F)
  165. 165 for i in 0..<n {
  166. 166● let re = fft.data[i].re
  167. 167 let im = fft.data[i].im
  168. 168● let mag = (re * re + im * im).sqrt()
  169. 169 let m = if log_scale {
  170. 170● Float::from_double(@math.log2(mag.to_double() + 1.0) * 0.6931471805599453)
  171. 171 } else {
  172. 172● mag
  173. 173 }
  174. 174 mags[i] = m
  175. 175 if m > max_mag {
  176. 176● max_mag = m
  177. 177 }
  178. 178 }
  179. 179 if max_mag > 0.0F {
  180. 180● for i in 0..<n {
  181. 181● let v = mags[i] / max_mag * 255.0F
  182. 182 let clamped = if v < 0.0F {
  183. 183○ 0
  184. 184● } else if v > 255.0F {
  185. 185○ 255
  186. 186 } else {
  187. 187● v.to_int()
  188. 188 }
  189. 189● out[i] = clamped.to_byte()
  190. 190 }
  191. 191 }
  192. 192 @types.Image::{
  193. 193 width: fft.width,
  194. 194 height: fft.height,
  195. 195 channels: 1,
  196. 196● data: Bytes::from_array(out),
  197. 197 }
  198. 198}
  199. 199
  200. 200///|
  201. 201/// 将零频率移到中心(fftshift)
  202. 202pub fn fft_shift(fft : FFTResult) -> FFTResult {
  203. 203● let w = fft.width
  204. 204 let h = fft.height
  205. 205● let data : Array[Complex] = Array::make(w * h, Complex::{
  206. 206 re: 0.0F,
  207. 207 im: 0.0F,
  208. 208 })
  209. 209 let cy = h / 2
  210. 210 let cx = w / 2
  211. 211 for y in 0..<h {
  212. 212● for x in 0..<w {
  213. 213● let sy = (y + cy) % h
  214. 214 let sx = (x + cx) % w
  215. 215 data[y * w + x] = fft.data[sy * w + sx]
  216. 216 }
  217. 217 }
  218. 218 FFTResult::{ width: w, height: h, data, }
  219. 219}
  220. 220
  221. 221///|
  222. 222/// 原地 fft_shift,避免分配新数组
  223. 223fn fft_shift_inplace(fft : FFTResult) -> Unit {
  224. 224● let w = fft.width
  225. 225 let h = fft.height
  226. 226 let cy = h / 2
  227. 227 let cx = w / 2
  228. 228 for y in 0..<h {
  229. 229● for x in 0..<w {
  230. 230● let sy = (y + cy) % h
  231. 231 let sx = (x + cx) % w
  232. 232 let src_idx = sy * w + sx
  233. 233 let dst_idx = y * w + x
  234. 234 if src_idx > dst_idx {
  235. 235● let tmp = fft.data[dst_idx]
  236. 236 fft.data[dst_idx] = fft.data[src_idx]
  237. 237 fft.data[src_idx] = tmp
  238. 238 }
  239. 239 }
  240. 240 }
  241. 241}
  242. 242
  243. 243///|
  244. 244/// 1D 原地 FFT(Cooley-Tukey radix-2),分离实虚部数组版本
  245. 245/// inverse=true 时做逆变换(不含归一化,归一化由调用方负责)
  246. 246fn fft_1d_split(re : Array[Float], im : Array[Float], inverse : Bool) -> Unit {
  247. 247● let n = re.length()
  248. 248 if n <= 1 {
  249. 249● return
  250. 250 }
  251. 251● bit_reverse_split(re, im)
  252. 252● let sign : Float = if inverse { 1.0F } else { -1.0F }
  253. 253 let mut size = 2
  254. 254 while size <= n {
  255. 255● let half = size / 2
  256. 256● let theta = sign * 2.0F * 3.141592653589793F / Float::from_int(size)
  257. 257● let w_re = @math.cosf(theta)
  258. 258● let w_im = @math.sinf(theta)
  259. 259 let mut i = 0
  260. 260 while i < n {
  261. 261● let mut wr = 1.0F
  262. 262 let mut wi = 0.0F
  263. 263 for j in 0..<half {
  264. 264● let idx1 = i + j
  265. 265 let idx2 = i + j + half
  266. 266 let a2_re = re[idx2]
  267. 267 let a2_im = im[idx2]
  268. 268 let tr = wr * a2_re - wi * a2_im
  269. 269 let ti = wr * a2_im + wi * a2_re
  270. 270 let a1_re = re[idx1]
  271. 271 let a1_im = im[idx1]
  272. 272 re[idx2] = a1_re - tr
  273. 273 im[idx2] = a1_im - ti
  274. 274 re[idx1] = a1_re + tr
  275. 275 im[idx1] = a1_im + ti
  276. 276 let new_wr = wr * w_re - wi * w_im
  277. 277 let new_wi = wr * w_im + wi * w_re
  278. 278 wr = new_wr
  279. 279 wi = new_wi
  280. 280 }
  281. 281 i += size
  282. 282 }
  283. 283 size *= 2
  284. 284 }
  285. 285}
  286. 286
  287. 287///|
  288. 288fn bit_reverse_split(re : Array[Float], im : Array[Float]) -> Unit {
  289. 289● let n = re.length()
  290. 290 if n <= 1 {
  291. 291○ return
  292. 292 }
  293. 293● let bits = log2_int(n)
  294. 294 let high_bit = 1 << (bits - 1)
  295. 295 // 递推预计算 bit reversal:rev[i] = (rev[i>>1] >> 1) | ((i&1) << (bits-1))
  296. 296● let rev : Array[Int32] = Array::make(n, 0)
  297. 297 for i in 1..<n {
  298. 298● rev[i] = (rev[i >> 1] >> 1) | (if (i & 1) != 0 { high_bit } else { 0 })
  299. 299 }
  300. 300 for i in 0..<n {
  301. 301● let j = rev[i]
  302. 302 if j > i {
  303. 303● let tmp_re = re[i]
  304. 304 let tmp_im = im[i]
  305. 305 re[i] = re[j]
  306. 306 im[i] = im[j]
  307. 307 re[j] = tmp_re
  308. 308 im[j] = tmp_im
  309. 309 }
  310. 310 }
  311. 311}
  312. 312
  313. 313///|
  314. 314fn log2_int(n : Int32) -> Int32 {
  315. 315● let mut k = 0
  316. 316 let mut v = n
  317. 317 while v > 1 {
  318. 318● v = v >> 1
  319. 319 k += 1
  320. 320 }
  321. 321 k
  322. 322}
  323. 323
  324. 324///|
  325. 325fn next_pow2(n : Int32) -> Int32 {
  326. 326● let mut p = 1
  327. 327 while p < n {
  328. 328● p *= 2
  329. 329 }
  330. 330 p
  331. 331}