image.process\filter\redact.mbt
80% · 28 / 35 points · 87 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # 块均值打码 - 3
/// - 4
/// 区域内每个 `block × block` 单元被自身均值填平。选块均值而不是纯色覆盖的理由: - 5
/// 纯色会让读者以为"那里本来就没东西",块均值能看出"有个东西但看不出是什么", - 6
/// 更符合"脱敏"而不是"抹除"的语义。 - 7
/// - 8
/// 区域先按图边界夹取(负坐标归零、超出部分裁掉);完全落在图外才报错, - 9
/// 因为调用方通常拿的是检测框或手写坐标,差几个像素不该整单失败。 - 10
- 11
///| - 12
pub fn redact_blocks( - 13
img : @types.Image, - 14
r : @types.Region, - 15
block : Int32, - 16
) -> @types.Image raise @types.ImageError { - 17●
if r.w <= 0 || r.h <= 0 { - 18○
raise @types.ImageError::Process( - 19
@types.ErrorCode::InvalidArgument, - 20
"打码区域宽高必须为正(收到 \{r.x},\{r.y},\{r.w},\{r.h})", - 21
) - 22
} - 23◐
let x0 = if r.x < 0 { 0 } else { r.x } - 24◐
let y0 = if r.y < 0 { 0 } else { r.y } - 25◐
let x1 = if r.x + r.w > img.width { img.width } else { r.x + r.w } - 26◐
let y1 = if r.y + r.h > img.height { img.height } else { r.y + r.h } - 27
if x1 <= x0 || y1 <= y0 { - 28○
raise @types.ImageError::Process( - 29
@types.ErrorCode::InvalidArgument, - 30
"打码区域完全在图外(图 \{img.width}x\{img.height},区域 \{r.x},\{r.y},\{r.w},\{r.h})", - 31
) - 32
} - 33◐
let br = if block < 1 { 1 } else { block } - 34
let ch = img.channels - 35
let src = img.data - 36
let dst : Array[Byte] = [] - 37●
for i in 0..<src.length() { - 38●
dst.push(src[i]) - 39
} - 40
let mut by = y0 - 41
while by < y1 { - 42●
let bh = if by + br > y1 { y1 - by } else { br } - 43
let mut bx = x0 - 44
while bx < x1 { - 45●
let bw = if bx + br > x1 { x1 - bx } else { br } - 46●
let sums = Array::make(ch, 0) - 47
for yy in 0..<bh { - 48●
for xx in 0..<bw { - 49●
let off = ((by + yy) * img.width + (bx + xx)) * ch - 50
for c in 0..<ch { - 51●
sums[c] += src[off + c].to_int() - 52
} - 53
} - 54
} - 55
let count = bw * bh - 56
let means : Array[Byte] = [] - 57
for c in 0..<ch { - 58●
means.push((sums[c] / count).to_byte()) - 59
} - 60
for yy in 0..<bh { - 61●
for xx in 0..<bw { - 62●
let off = ((by + yy) * img.width + (bx + xx)) * ch - 63
for c in 0..<ch { - 64●
dst[off + c] = means[c] - 65
} - 66
} - 67
} - 68
bx += bw - 69
} - 70
by += bh - 71
} - 72
{ - 73
width: img.width, - 74
height: img.height, - 75
channels: ch, - 76●
data: Bytes::from_array(dst), - 77
} - 78
} - 79
- 80
///| - 81
/// 全图打码:不给坐标时的保守选择。 - 82
pub fn redact_blocks_all( - 83
img : @types.Image, - 84
block : Int32, - 85
) -> @types.Image raise @types.ImageError { - 86●
redact_blocks(img, { x: 0, y: 0, w: img.width, h: img.height, }, block) - 87
}