image.process\color\quantize.mbt

90.2% · 138 / 153 points · 428 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/// # 量化 quantize
  3. 3///
  4. 4/// 图像处理算法模块
  5. 5/// 图像处理算法模块 Image processing algorithm module
  6. 6// 色彩量化(纯 MoonBit):Floyd-Steinberg 抖动 + Median Cut + K-means 量化
  7. 7
  8. 8///|
  9. 9/// Floyd-Steinberg 误差扩散抖动量化。
  10. 10/// levels 为每通道量化级别数(如 levels=2 → 0/255,levels=4 → 0/85/170/255)。
  11. 11/// 仅处理颜色通道,alpha 不变。
  12. 12pub fn floyd_steinberg(
  13. 13 img : @types.Image,
  14. 14 levels : 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 "floyd_steinberg: 图像尺寸必须大于0",
  20. 20 )
  21. 21 }
  22. 22 if img.channels < 1 || img.channels > 4 {
  23. 23○ raise @types.LoadError::DecodeFailed(
  24. 24 "floyd_steinberg: 通道数必须在1-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 "floyd_steinberg: 数据大小不匹配,期望 " +
  31. 31○ expected_size.to_string() +
  32. 32 ",实际 " +
  33. 33○ img.data.length().to_string(),
  34. 34 )
  35. 35 }
  36. 36 if levels < 2 {
  37. 37● raise @types.LoadError::DecodeFailed("floyd_steinberg: levels必须>=2")
  38. 38 }
  39. 39 let ch = img.channels
  40. 40● let color_ch = if ch >= 3 { 3 } else { ch }
  41. 41 let w = img.width
  42. 42 let h = img.height
  43. 43 let n = w * h
  44. 44 // 可变像素缓冲
  45. 45● let buf : Array[Int32] = Array::make(n * color_ch, 0)
  46. 46 for i in 0..<n {
  47. 47● for c in 0..<color_ch {
  48. 48● buf[i * color_ch + c] = img.data[i * ch + c].to_int()
  49. 49 }
  50. 50 }
  51. 51 let step = 255 / (levels - 1)
  52. 52 let half_step = step / 2
  53. 53 // Floyd-Steinberg 抖动
  54. 54 for y in 0..<h {
  55. 55● for x in 0..<w {
  56. 56● for c in 0..<color_ch {
  57. 57● let idx = (y * w + x) * color_ch + c
  58. 58● let old_val = buf[idx].clamp(min=0, max=255)
  59. 59● let new_val = ((old_val + half_step) / step * step).clamp(
  60. 60 min=0,
  61. 61 max=255,
  62. 62 )
  63. 63 buf[idx] = new_val
  64. 64 let err = old_val - new_val
  65. 65 // 误差扩散:右 7/16, 左下 3/16, 下 5/16, 右下 1/16
  66. 66 if x + 1 < w {
  67. 67● buf[(y * w + x + 1) * color_ch + c] += err * 7 / 16
  68. 68 }
  69. 69 if y + 1 < h {
  70. 70● if x > 0 {
  71. 71● buf[((y + 1) * w + x - 1) * color_ch + c] += err * 3 / 16
  72. 72 }
  73. 73 buf[((y + 1) * w + x) * color_ch + c] += err * 5 / 16
  74. 74 if x + 1 < w {
  75. 75● buf[((y + 1) * w + x + 1) * color_ch + c] += err / 16
  76. 76 }
  77. 77 }
  78. 78 }
  79. 79 }
  80. 80 }
  81. 81 // 输出
  82. 82● let out : Array[Byte] = Array::make(n * ch, b'\x00')
  83. 83 for i in 0..<n {
  84. 84● for c in 0..<color_ch {
  85. 85● out[i * ch + c] = buf[i * color_ch + c].clamp(min=0, max=255).to_byte()
  86. 86 }
  87. 87 if ch == 4 {
  88. 88● out[i * ch + 3] = img.data[i * ch + 3]
  89. 89 }
  90. 90 }
  91. 91 @types.Image::{
  92. 92 width: w,
  93. 93 height: h,
  94. 94 channels: ch,
  95. 95● data: Bytes::from_array(out),
  96. 96 }
  97. 97}
  98. 98
  99. 99///|
  100. 100/// Median Cut 色彩量化。将图像量化为最多 num_colors 种颜色。
  101. 101/// 返回量化后的 RGB 图像(channels=3)。
  102. 102/// 算法:递归地沿最大方差通道在中位数处分割颜色空间。
  103. 103pub fn median_cut(
  104. 104 img : @types.Image,
  105. 105 num_colors : Int32,
  106. 106) -> @types.Image raise @types.LoadError {
  107. 107 // 输入验证
  108. 108● if img.width <= 0 || img.height <= 0 {
  109. 109● raise @types.LoadError::DecodeFailed(
  110. 110 "median_cut: 图像尺寸必须大于0",
  111. 111 )
  112. 112 }
  113. 113 if img.channels < 1 || img.channels > 4 {
  114. 114○ raise @types.LoadError::DecodeFailed(
  115. 115 "median_cut: 通道数必须在1-4之间",
  116. 116 )
  117. 117 }
  118. 118 let expected_size = img.width * img.height * img.channels
  119. 119● if img.data.length() != expected_size {
  120. 120○ raise @types.LoadError::DecodeFailed(
  121. 121 "median_cut: 数据大小不匹配,期望 " +
  122. 122○ expected_size.to_string() +
  123. 123 ",实际 " +
  124. 124○ img.data.length().to_string(),
  125. 125 )
  126. 126 }
  127. 127 if num_colors < 2 {
  128. 128● return to_rgb(img)
  129. 129 }
  130. 130 let w = img.width
  131. 131 let h = img.height
  132. 132 let n = w * h
  133. 133 // 收集所有 RGB 像素
  134. 134● let pixels : Array[(Int32, Int32, Int32)] = Array::make(n, (0, 0, 0))
  135. 135 let ch = img.channels
  136. 136● let data_int : Array[Int32] = Array::make(n * ch, 0)
  137. 137 for i in 0..<(n * ch) {
  138. 138● data_int[i] = img.data[i].to_int()
  139. 139 }
  140. 140 for i in 0..<n {
  141. 141● let r = data_int[i * ch]
  142. 142● let g = if ch >= 2 { data_int[i * ch + 1] } else { r }
  143. 143● let b = if ch >= 3 { data_int[i * ch + 2] } else { r }
  144. 144 pixels[i] = (r, g, b)
  145. 145 }
  146. 146 // 初始 bucket 包含所有像素索引
  147. 147● let initial_bucket : Array[Int32] = Array::make(n, 0)
  148. 148 for i in 0..<n {
  149. 149● initial_bucket[i] = i
  150. 150 }
  151. 151 // 递归分割
  152. 152 let buckets : Array[Array[Int32]] = [initial_bucket]
  153. 153 let mut num_buckets = 1
  154. 154 while num_buckets < num_colors {
  155. 155 // 找到范围最大的 bucket
  156. 156● let mut best_bucket_idx = -1
  157. 157 let mut best_range = 0
  158. 158● for bi in 0..<buckets.length() {
  159. 159● if buckets[bi].length() < 2 {
  160. 160● continue
  161. 161 }
  162. 162● let (range, _ch) = bucket_max_range(pixels, buckets[bi])
  163. 163 if range > best_range {
  164. 164● best_range = range
  165. 165 best_bucket_idx = bi
  166. 166 }
  167. 167 }
  168. 168 if best_bucket_idx < 0 {
  169. 169● break
  170. 170 }
  171. 171 // 分割最佳 bucket
  172. 172 let bucket = buckets[best_bucket_idx]
  173. 173● let (_, split_ch) = bucket_max_range(pixels, bucket)
  174. 174 // 按分割通道排序
  175. 175● let sorted = bucket.copy()
  176. 176● sorted.sort_by(fn(a, b) {
  177. 177● let va = channel_value(pixels[a], split_ch)
  178. 178● let vb = channel_value(pixels[b], split_ch)
  179. 179● va.compare(vb)
  180. 180 })
  181. 181● let mid = sorted.length() / 2
  182. 182● let left : Array[Int32] = Array::make(mid, 0)
  183. 183● let right : Array[Int32] = Array::make(sorted.length() - mid, 0)
  184. 184 for i in 0..<mid {
  185. 185● left[i] = sorted[i]
  186. 186 }
  187. 187● for i in mid..<sorted.length() {
  188. 188● right[i - mid] = sorted[i]
  189. 189 }
  190. 190 buckets[best_bucket_idx] = left
  191. 191● buckets.push(right)
  192. 192 num_buckets += 1
  193. 193 }
  194. 194 // 计算每个 bucket 的平均色作为调色板
  195. 195● let palette : Array[(Int32, Int32, Int32)] = Array::make(
  196. 196● buckets.length(),
  197. 197 (0, 0, 0),
  198. 198 )
  199. 199● for bi in 0..<buckets.length() {
  200. 200● palette[bi] = bucket_average(pixels, buckets[bi])
  201. 201 }
  202. 202 // 映射每个像素到最近的调色板颜色
  203. 203● let out : Array[Byte] = Array::make(n * 3, b'\x00')
  204. 204 for i in 0..<n {
  205. 205● let (r, g, b) = pixels[i]
  206. 206 let mut best_idx = 0
  207. 207 let mut best_dist = 999999
  208. 208● for pi in 0..<palette.length() {
  209. 209● let (pr, pg, pb) = palette[pi]
  210. 210 let dist = (r - pr) * (r - pr) + (g - pg) * (g - pg) + (b - pb) * (b - pb)
  211. 211 if dist < best_dist {
  212. 212● best_dist = dist
  213. 213 best_idx = pi
  214. 214 }
  215. 215 }
  216. 216 let (pr, pg, pb) = palette[best_idx]
  217. 217● out[i * 3] = pr.to_byte()
  218. 218● out[i * 3 + 1] = pg.to_byte()
  219. 219● out[i * 3 + 2] = pb.to_byte()
  220. 220 }
  221. 221 @types.Image::{
  222. 222 width: w,
  223. 223 height: h,
  224. 224 channels: 3,
  225. 225● data: Bytes::from_array(out),
  226. 226 }
  227. 227}
  228. 228
  229. 229///|
  230. 230/// K-means 色彩量化。将图像颜色聚为 k 类,每类用聚类中心替代。
  231. 231/// 适用于 RGB/RGBA 图像(channels=3/4),alpha 通道不变。
  232. 232/// max_iters 控制最大迭代次数(默认 20)。
  233. 233pub fn kmeans_quantize(
  234. 234 img : @types.Image,
  235. 235 k : Int32,
  236. 236 max_iters : Int32,
  237. 237) -> @types.Image raise @types.LoadError {
  238. 238● if k < 1 || k > 256 {
  239. 239● raise @types.LoadError::DecodeFailed("k 必须在 1..256 之间")
  240. 240 }
  241. 241 if img.channels != 3 && img.channels != 4 {
  242. 242● raise @types.LoadError::DecodeFailed(
  243. 243 "kmeans_quantize 需要 RGB/RGBA 图像",
  244. 244 )
  245. 245 }
  246. 246 let ch = img.channels
  247. 247 let n = img.width * img.height
  248. 248 if n == 0 {
  249. 249● return img
  250. 250 }
  251. 251 // 初始化聚类中心:均匀采样
  252. 252● let centroids_r : Array[Int32] = Array::make(k, 0)
  253. 253● let centroids_g : Array[Int32] = Array::make(k, 0)
  254. 254● let centroids_b : Array[Int32] = Array::make(k, 0)
  255. 255● let data_int : Array[Int32] = Array::make(n * ch, 0)
  256. 256 for i in 0..<(n * ch) {
  257. 257● data_int[i] = img.data[i].to_int()
  258. 258 }
  259. 259◐ let step = if n > k { n / k } else { 1 }
  260. 260 for i in 0..<k {
  261. 261● let idx = (i * step).clamp(min=0, max=n - 1)
  262. 262 centroids_r[i] = data_int[idx * ch]
  263. 263 centroids_g[i] = data_int[idx * ch + 1]
  264. 264 centroids_b[i] = data_int[idx * ch + 2]
  265. 265 }
  266. 266 // 迭代
  267. 267● let labels : Array[Int32] = Array::make(n, 0)
  268. 268◐ let iters = if max_iters < 1 { 20 } else { max_iters }
  269. 269 for _ in 0..<iters {
  270. 270 // 分配每个像素到最近的聚类
  271. 271● let mut changed = false
  272. 272 for i in 0..<n {
  273. 273● let r = data_int[i * ch]
  274. 274 let g = data_int[i * ch + 1]
  275. 275 let b = data_int[i * ch + 2]
  276. 276 let mut best = 0
  277. 277● let mut best_dist = dist_sq(
  278. 278 r,
  279. 279 g,
  280. 280 b,
  281. 281 centroids_r[0],
  282. 282 centroids_g[0],
  283. 283 centroids_b[0],
  284. 284 )
  285. 285 for j in 1..<k {
  286. 286● let d = dist_sq(r, g, b, centroids_r[j], centroids_g[j], centroids_b[j])
  287. 287 if d < best_dist {
  288. 288● best_dist = d
  289. 289 best = j
  290. 290 }
  291. 291 }
  292. 292 if labels[i] != best {
  293. 293● changed = true
  294. 294 labels[i] = best
  295. 295 }
  296. 296 }
  297. 297 if !changed {
  298. 298● break
  299. 299 }
  300. 300
  301. 301 // 更新聚类中心
  302. 302● let sum_r : Array[Int32] = Array::make(k, 0)
  303. 303● let sum_g : Array[Int32] = Array::make(k, 0)
  304. 304● let sum_b : Array[Int32] = Array::make(k, 0)
  305. 305● let cnt : Array[Int32] = Array::make(k, 0)
  306. 306 for i in 0..<n {
  307. 307● let label = labels[i]
  308. 308 sum_r[label] += data_int[i * ch]
  309. 309 sum_g[label] += data_int[i * ch + 1]
  310. 310 sum_b[label] += data_int[i * ch + 2]
  311. 311 cnt[label] += 1
  312. 312 }
  313. 313 for j in 0..<k {
  314. 314● if cnt[j] > 0 {
  315. 315● centroids_r[j] = sum_r[j] / cnt[j]
  316. 316 centroids_g[j] = sum_g[j] / cnt[j]
  317. 317 centroids_b[j] = sum_b[j] / cnt[j]
  318. 318 }
  319. 319 }
  320. 320 }
  321. 321 // 生成输出
  322. 322● let out : Array[Byte] = Array::make(n * ch, b'\x00')
  323. 323 for i in 0..<n {
  324. 324● let label = labels[i]
  325. 325● out[i * ch] = centroids_r[label].to_byte()
  326. 326● out[i * ch + 1] = centroids_g[label].to_byte()
  327. 327● out[i * ch + 2] = centroids_b[label].to_byte()
  328. 328 if ch == 4 {
  329. 329● out[i * ch + 3] = img.data[i * ch + 3]
  330. 330 }
  331. 331 }
  332. 332 @types.Image::{
  333. 333 width: img.width,
  334. 334 height: img.height,
  335. 335 channels: ch,
  336. 336● data: Bytes::from_array(out),
  337. 337 }
  338. 338}
  339. 339
  340. 340///|
  341. 341fn channel_value(pixel : (Int32, Int32, Int32), ch : Int32) -> Int32 {
  342. 342● match ch {
  343. 343● 0 => pixel.0
  344. 344● 1 => pixel.1
  345. 345○ _ => pixel.2
  346. 346 }
  347. 347}
  348. 348
  349. 349///|
  350. 350fn bucket_max_range(
  351. 351 pixels : Array[(Int32, Int32, Int32)],
  352. 352 bucket : Array[Int32],
  353. 353) -> (Int32, Int32) {
  354. 354● let mut min_r = 255
  355. 355 let mut max_r = 0
  356. 356 let mut min_g = 255
  357. 357 let mut max_g = 0
  358. 358 let mut min_b = 255
  359. 359 let mut max_b = 0
  360. 360● for i in 0..<bucket.length() {
  361. 361● let (r, g, b) = pixels[bucket[i]]
  362. 362 if r < min_r {
  363. 363● min_r = r
  364. 364 }
  365. 365 if r > max_r {
  366. 366● max_r = r
  367. 367 }
  368. 368 if g < min_g {
  369. 369● min_g = g
  370. 370 }
  371. 371 if g > max_g {
  372. 372● max_g = g
  373. 373 }
  374. 374 if b < min_b {
  375. 375● min_b = b
  376. 376 }
  377. 377 if b > max_b {
  378. 378● max_b = b
  379. 379 }
  380. 380 }
  381. 381 let range_r = max_r - min_r
  382. 382 let range_g = max_g - min_g
  383. 383 let range_b = max_b - min_b
  384. 384 if range_r >= range_g && range_r >= range_b {
  385. 385● (range_r, 0)
  386. 386● } else if range_g >= range_b {
  387. 387● (range_g, 1)
  388. 388 } else {
  389. 389○ (range_b, 2)
  390. 390 }
  391. 391}
  392. 392
  393. 393///|
  394. 394fn bucket_average(
  395. 395 pixels : Array[(Int32, Int32, Int32)],
  396. 396 bucket : Array[Int32],
  397. 397) -> (Int32, Int32, Int32) {
  398. 398● let mut sum_r = 0
  399. 399 let mut sum_g = 0
  400. 400 let mut sum_b = 0
  401. 401● for i in 0..<bucket.length() {
  402. 402● let (r, g, b) = pixels[bucket[i]]
  403. 403 sum_r += r
  404. 404 sum_g += g
  405. 405 sum_b += b
  406. 406 }
  407. 407● let len = bucket.length()
  408. 408 if len == 0 {
  409. 409○ (0, 0, 0)
  410. 410 } else {
  411. 411● (sum_r / len, sum_g / len, sum_b / len)
  412. 412 }
  413. 413}
  414. 414
  415. 415///|
  416. 416fn dist_sq(
  417. 417 r1 : Int32,
  418. 418 g1 : Int32,
  419. 419 b1 : Int32,
  420. 420 r2 : Int32,
  421. 421 g2 : Int32,
  422. 422 b2 : Int32,
  423. 423) -> Int32 {
  424. 424● let dr = r1 - r2
  425. 425 let dg = g1 - g2
  426. 426 let db = b1 - b2
  427. 427 dr * dr + dg * dg + db * db
  428. 428}