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