image.process\filter\redact.mbt

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