image.domain\forensics\tamper_detection.mbt

93.1% · 243 / 261 points · 813 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/// # 篡改检测 forensics/tamper_detection
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 图像来源鉴定增强(v27.1.0)
  7. 7// ELA 分析、噪声残差、DCT 系数、双 JPEG 检测、克隆检测、光照一致性、篡改检测综合
  8. 8
  9. 9///|
  10. 10/// ELA 分析结果
  11. 11pub(all) struct ElaAnalysisResult {
  12. 12 ela_mean : Double
  13. 13 ela_std : Double
  14. 14 ela_max : Double
  15. 15 ela_distribution : Array[Double]
  16. 16 tampered_region_ratio : Double
  17. 17}
  18. 18
  19. 19///|
  20. 20/// 噪声残差分析结果
  21. 21pub(all) struct NoiseResidualResult {
  22. 22 residual_mean : Double
  23. 23 residual_std : Double
  24. 24 residual_energy : Double
  25. 25 sensor_pattern : Array[Double]
  26. 26 pattern_consistency : Double
  27. 27}
  28. 28
  29. 29///|
  30. 30/// DCT 系数分析结果
  31. 31pub(all) struct DctCoefficientResult {
  32. 32 coefficient_distribution : Array[Double]
  33. 33 high_freq_coefficient_ratio : Double
  34. 34 zero_coefficient_ratio : Double
  35. 35 blockiness_artifact : Double
  36. 36 double_jpeg_indicator : Double
  37. 37}
  38. 38
  39. 39///|
  40. 40/// 克隆检测结果
  41. 41pub(all) struct CloneDetectionResult {
  42. 42 clone_region_count : Int32
  43. 43 clone_regions : Array[(Int32, Int32, Int32, Int32)]
  44. 44 clone_similarity : Double
  45. 45 has_clone : Bool
  46. 46}
  47. 47
  48. 48///|
  49. 49/// 光照一致性结果
  50. 50pub(all) struct IlluminationConsistencyResult {
  51. 51 illumination_direction : Double
  52. 52 shadow_consistency : Double
  53. 53 highlight_distribution : Double
  54. 54 illumination_inconsistency : Double
  55. 55 has_inconsistent_lighting : Bool
  56. 56}
  57. 57
  58. 58///|
  59. 59/// 篡改检测综合结果
  60. 60pub(all) struct TamperDetectionResult {
  61. 61 is_tampered : Bool
  62. 62 tamper_probability : Double
  63. 63 tamper_type : String
  64. 64 tampered_regions : Array[(Int32, Int32, Int32, Int32)]
  65. 65 confidence : Double
  66. 66 analysis_details : String
  67. 67}
  68. 68
  69. 69///|
  70. 70/// 元数据取证结果
  71. 71pub(all) struct MetadataForensicsResult {
  72. 72 has_metadata : Bool
  73. 73 software_signature : String
  74. 74 creation_time : String
  75. 75 device_info : String
  76. 76 metadata_consistency : Double
  77. 77 has_inconsistency : Bool
  78. 78}
  79. 79
  80. 80///|
  81. 81/// JPEG ghost 分析结果
  82. 82pub(all) struct JpegGhostResult {
  83. 83 ghost_quality_levels : Array[Int32]
  84. 84 ghost_region_count : Int32
  85. 85 has_ghost : Bool
  86. 86 primary_quality : Int32
  87. 87 secondary_quality : Int32
  88. 88}
  89. 89
  90. 90///|
  91. 91/// CFA 分析结果
  92. 92pub(all) struct CfaAnalysisResult {
  93. 93 cfa_pattern : String
  94. 94 bayer_pattern_score : Double
  95. 95 cfa_artifact_level : Double
  96. 96 is_cfa_consistent : Bool
  97. 97}
  98. 98
  99. 99///|
  100. 100/// ELA(Error Level Analysis)分析
  101. 101/// 通过模拟 JPEG 重压缩分析图像篡改区域
  102. 102pub fn analyze_ela(
  103. 103 img : @types.Image,
  104. 104 quality_level : Int32,
  105. 105) -> ElaAnalysisResult raise @types.LoadError {
  106. 106● let w = img.width
  107. 107 let h = img.height
  108. 108 let total = w * h
  109. 109
  110. 110 // 模拟 JPEG 量化:按 quality_level 量化像素
  111. 111● let quant = if quality_level > 0 { 256 / (quality_level + 1) } else { 8 }
  112. 112 if quant == 0 {
  113. 113● raise @types.LoadError::DecodeFailed("quality_level too high")
  114. 114 }
  115. 115
  116. 116 // 量化并反量化(模拟 JPEG 压缩-解压)
  117. 117 let recompressed : Array[Byte] = []
  118. 118 for i in 0..<total {
  119. 119● let val = img.data[i].to_int()
  120. 120 let quantized = val / quant * quant
  121. 121 let clamped = if quantized < 0 {
  122. 122○ 0
  123. 123● } else if quantized > 255 {
  124. 124○ 255
  125. 125 } else {
  126. 126● quantized
  127. 127 }
  128. 128● recompressed.push(clamped.to_byte())
  129. 129 }
  130. 130
  131. 131 // 计算 ELA 差值
  132. 132 let mut ela_mean = 0.0
  133. 133 let mut ela_max = 0.0
  134. 134 let mut ela_sq_sum = 0.0
  135. 135 let distribution : Array[Double] = []
  136. 136 let num_bins = 16
  137. 137 for _ in 0..<num_bins {
  138. 138● distribution.push(0.0)
  139. 139 }
  140. 140
  141. 141 for i in 0..<total {
  142. 142● let diff = (img.data[i].to_int() - recompressed[i].to_int())
  143. 143● .abs()
  144. 144● .to_double()
  145. 145 ela_mean += diff
  146. 146 if diff > ela_max {
  147. 147● ela_max = diff
  148. 148 }
  149. 149 ela_sq_sum += diff * diff
  150. 150● let bin = (diff.to_int() * num_bins / 256).clamp(min=0, max=num_bins - 1)
  151. 151 distribution[bin] += 1.0
  152. 152 }
  153. 153
  154. 154● ela_mean /= total.to_double()
  155. 155● let ela_std = (ela_sq_sum / total.to_double() - ela_mean * ela_mean)
  156. 156● .abs()
  157. 157● .sqrt()
  158. 158
  159. 159 // 归一化分布
  160. 160 for i in 0..<num_bins {
  161. 161● distribution[i] /= total.to_double()
  162. 162 }
  163. 163
  164. 164 // 篡改区域比例:ELA 值高于均值的像素比例
  165. 165 let mut tampered_count = 0
  166. 166 for i in 0..<total {
  167. 167● let diff = (img.data[i].to_int() - recompressed[i].to_int())
  168. 168● .abs()
  169. 169● .to_double()
  170. 170 if diff > ela_mean * 2.0 {
  171. 171● tampered_count += 1
  172. 172 }
  173. 173 }
  174. 174● let tampered_ratio = tampered_count.to_double() / total.to_double()
  175. 175
  176. 176 ElaAnalysisResult::{
  177. 177 ela_mean,
  178. 178 ela_std,
  179. 179 ela_max,
  180. 180 ela_distribution: distribution,
  181. 181 tampered_region_ratio: tampered_ratio,
  182. 182 }
  183. 183}
  184. 184
  185. 185///|
  186. 186/// 噪声残差分析
  187. 187/// 提取传感器模式噪声残差
  188. 188pub fn analyze_noise_residual(img : @types.Image) -> NoiseResidualResult {
  189. 189● let w = img.width
  190. 190 let h = img.height
  191. 191 let total = w * h
  192. 192
  193. 193 // 提取噪声残差:原图 - 中值滤波结果
  194. 194 let residual : Array[Double] = []
  195. 195 for y in 0..<h {
  196. 196● for x in 0..<w {
  197. 197● let idx = y * w + x
  198. 198 // 3x3 中值滤波
  199. 199 let neighbors : Array[Int32] = []
  200. 200 for dy in -1..<2 {
  201. 201● for dx in -1..<2 {
  202. 202● let ny = y + dy
  203. 203 let nx = x + dx
  204. 204 if ny >= 0 && ny < h && nx >= 0 && nx < w {
  205. 205● neighbors.push(img.data[ny * w + nx].to_int())
  206. 206 }
  207. 207 }
  208. 208 }
  209. 209● neighbors.sort()
  210. 210● let median = neighbors[neighbors.length() / 2]
  211. 211● let r = img.data[idx].to_double() - median.to_double()
  212. 212● residual.push(r)
  213. 213 }
  214. 214 }
  215. 215
  216. 216 // 统计
  217. 217 let mut mean = 0.0
  218. 218 let mut sq_sum = 0.0
  219. 219 for i in 0..<total {
  220. 220● mean += residual[i]
  221. 221 sq_sum += residual[i] * residual[i]
  222. 222 }
  223. 223● mean /= total.to_double()
  224. 224● let std = (sq_sum / total.to_double() - mean * mean).abs().sqrt()
  225. 225● let energy = sq_sum / total.to_double()
  226. 226
  227. 227 // 传感器模式(行均值作为简化模式)
  228. 228 let sensor_pattern : Array[Double] = []
  229. 229● let row_count = if h < 8 { h } else { 8 }
  230. 230 for r in 0..<row_count {
  231. 231● let mut row_mean = 0.0
  232. 232 let row_len = w
  233. 233 for c in 0..<row_len {
  234. 234● row_mean += residual[r * w + c]
  235. 235 }
  236. 236● sensor_pattern.push(row_mean / row_len.to_double())
  237. 237 }
  238. 238
  239. 239 // 模式一致性:相邻行模式的相关性
  240. 240 let mut consistency = 0.0
  241. 241● if sensor_pattern.length() >= 2 {
  242. 242● for i in 0..<(sensor_pattern.length() - 1) {
  243. 243● consistency += (sensor_pattern[i] * sensor_pattern[i + 1]).abs()
  244. 244 }
  245. 245● consistency /= (sensor_pattern.length() - 1).to_double()
  246. 246 }
  247. 247
  248. 248 NoiseResidualResult::{
  249. 249 residual_mean: mean,
  250. 250 residual_std: std,
  251. 251 residual_energy: energy,
  252. 252 sensor_pattern,
  253. 253 pattern_consistency: consistency,
  254. 254 }
  255. 255}
  256. 256
  257. 257///|
  258. 258/// DCT 系数分析
  259. 259/// 分析 DCT 系数分布特征,检测双 JPEG 压缩
  260. 260pub fn analyze_dct_coefficients(img : @types.Image) -> DctCoefficientResult {
  261. 261● let w = img.width
  262. 262 let h = img.height
  263. 263
  264. 264 // 简化 DCT:计算 8x8 块的 DCT 系数统计
  265. 265 let block_size = 8
  266. 266 let num_blocks_x = w / block_size
  267. 267 let num_blocks_y = h / block_size
  268. 268 let num_blocks = num_blocks_x * num_blocks_y
  269. 269
  270. 270 let mut high_freq_count = 0
  271. 271 let mut zero_count = 0
  272. 272 let mut total_coeffs = 0
  273. 273 let mut blockiness = 0.0
  274. 274
  275. 275 let distribution : Array[Double] = []
  276. 276 let num_bins = 10
  277. 277 for _ in 0..<num_bins {
  278. 278● distribution.push(0.0)
  279. 279 }
  280. 280
  281. 281 for by in 0..<num_blocks_y {
  282. 282● for bx in 0..<num_blocks_x {
  283. 283 // 计算 8x8 块的简化 DCT
  284. 284● let mut dc = 0.0
  285. 285 let mut ac_energy = 0.0
  286. 286 for j in 0..<block_size {
  287. 287● for i in 0..<block_size {
  288. 288● let idx = (by * block_size + j) * w + (bx * block_size + i)
  289. 289● let val = img.data[idx].to_double()
  290. 290 dc += val
  291. 291 if i > 0 || j > 0 {
  292. 292● ac_energy += val * val
  293. 293 }
  294. 294 }
  295. 295 }
  296. 296● dc /= (block_size * block_size).to_double()
  297. 297
  298. 298 // 块边界不连续性
  299. 299 if bx > 0 {
  300. 300● let mut border_diff = 0.0
  301. 301 for j in 0..<block_size {
  302. 302● let idx_left = (by * block_size + j) * w + (bx * block_size - 1)
  303. 303 let idx_right = (by * block_size + j) * w + bx * block_size
  304. 304● border_diff += (img.data[idx_left].to_double() -
  305. 305● img.data[idx_right].to_double()).abs()
  306. 306 }
  307. 307● blockiness += border_diff / block_size.to_double()
  308. 308 }
  309. 309
  310. 310 total_coeffs += block_size * block_size
  311. 311 if ac_energy < 100.0 {
  312. 312○ zero_count += block_size * block_size - 1
  313. 313 }
  314. 314 if ac_energy > 1000.0 {
  315. 315● high_freq_count += block_size * block_size - 1
  316. 316 }
  317. 317
  318. 318 // 分布统计
  319. 319● let bin = (dc.to_int() * num_bins / 256).clamp(min=0, max=num_bins - 1)
  320. 320 distribution[bin] += 1.0
  321. 321 }
  322. 322 }
  323. 323
  324. 324 if num_blocks > 0 {
  325. 325● blockiness /= num_blocks.to_double()
  326. 326 }
  327. 327
  328. 328 let high_freq_ratio = if total_coeffs > 0 {
  329. 329● high_freq_count.to_double() / total_coeffs.to_double()
  330. 330 } else {
  331. 331● 0.0
  332. 332 }
  333. 333 let zero_ratio = if total_coeffs > 0 {
  334. 334● zero_count.to_double() / total_coeffs.to_double()
  335. 335 } else {
  336. 336● 0.0
  337. 337 }
  338. 338
  339. 339 // 归一化分布
  340. 340 if num_blocks > 0 {
  341. 341● for i in 0..<num_bins {
  342. 342● distribution[i] /= num_blocks.to_double()
  343. 343 }
  344. 344 }
  345. 345
  346. 346 // 双 JPEG 指示:DCT 系数分布有周期性峰值
  347. 347 let mut double_jpeg_indicator = 0.0
  348. 348 for i in 1..<(num_bins - 1) {
  349. 349● if distribution[i] > distribution[i - 1] &&
  350. 350 distribution[i] > distribution[i + 1] {
  351. 351● double_jpeg_indicator += 1.0
  352. 352 }
  353. 353 }
  354. 354● double_jpeg_indicator /= num_bins.to_double()
  355. 355
  356. 356 DctCoefficientResult::{
  357. 357 coefficient_distribution: distribution,
  358. 358 high_freq_coefficient_ratio: high_freq_ratio,
  359. 359 zero_coefficient_ratio: zero_ratio,
  360. 360 blockiness_artifact: blockiness,
  361. 361 double_jpeg_indicator,
  362. 362 }
  363. 363}
  364. 364
  365. 365///|
  366. 366/// 克隆检测(复制移动篡改检测)
  367. 367/// 检测图像中的复制移动区域
  368. 368pub fn detect_clone_regions(
  369. 369 img : @types.Image,
  370. 370 block_size : Int32,
  371. 371 threshold : Double,
  372. 372) -> CloneDetectionResult raise @types.LoadError {
  373. 373● let w = img.width
  374. 374 let h = img.height
  375. 375
  376. 376 if block_size < 2 || block_size > 16 {
  377. 377● raise @types.LoadError::DecodeFailed("block_size must be 2..16")
  378. 378 }
  379. 379
  380. 380 let num_blocks_x = w - block_size + 1
  381. 381 let num_blocks_y = h - block_size + 1
  382. 382
  383. 383 // 提取块特征(简化:均值+方差)
  384. 384 let block_features : Array[(Double, Double, Int32, Int32)] = []
  385. 385 for by in 0..<num_blocks_y {
  386. 386● for bx in 0..<num_blocks_x {
  387. 387● let mut mean = 0.0
  388. 388 let mut sq_sum = 0.0
  389. 389 let count = block_size * block_size
  390. 390 for j in 0..<block_size {
  391. 391● for i in 0..<block_size {
  392. 392● let idx = (by + j) * w + (bx + i)
  393. 393● let val = img.data[idx].to_double()
  394. 394 mean += val
  395. 395 sq_sum += val * val
  396. 396 }
  397. 397 }
  398. 398● mean /= count.to_double()
  399. 399● let variance = sq_sum / count.to_double() - mean * mean
  400. 400● block_features.push((mean, variance, bx, by))
  401. 401 }
  402. 402 }
  403. 403
  404. 404 // 比较块特征,找相似块
  405. 405 let clone_regions : Array[(Int32, Int32, Int32, Int32)] = []
  406. 406 let mut clone_count = 0
  407. 407 let mut total_similarity = 0.0
  408. 408 let mut comparison_count = 0
  409. 409
  410. 410● let n = block_features.length()
  411. 411 for i in 0..<n {
  412. 412● for j in 0..<n {
  413. 413● if i >= j {
  414. 414● continue
  415. 415 }
  416. 416 let (m1, v1, x1, y1) = block_features[i]
  417. 417 let (m2, v2, x2, y2) = block_features[j]
  418. 418 // 跳过相邻块
  419. 419● let dist = (x1 - x2).abs() + (y1 - y2).abs()
  420. 420 if dist < block_size * 2 {
  421. 421● continue
  422. 422 }
  423. 423● let mean_diff = (m1 - m2).abs()
  424. 424● let var_diff = (v1 - v2).abs()
  425. 425 let similarity = 1.0 / (1.0 + mean_diff / 10.0 + var_diff / 100.0)
  426. 426 total_similarity += similarity
  427. 427 comparison_count += 1
  428. 428 if similarity > threshold && clone_count < 20 {
  429. 429● clone_regions.push((x1, y1, x2, y2))
  430. 430 clone_count += 1
  431. 431 }
  432. 432 }
  433. 433 }
  434. 434
  435. 435 let avg_similarity = if comparison_count > 0 {
  436. 436● total_similarity / comparison_count.to_double()
  437. 437 } else {
  438. 438○ 0.0
  439. 439 }
  440. 440
  441. 441 CloneDetectionResult::{
  442. 442 clone_region_count: clone_count,
  443. 443 clone_regions,
  444. 444 clone_similarity: avg_similarity,
  445. 445 has_clone: clone_count > 0,
  446. 446 }
  447. 447}
  448. 448
  449. 449///|
  450. 450/// 光照一致性分析
  451. 451/// 分析图像光照方向一致性,检测合成图像
  452. 452pub fn analyze_illumination_consistency(
  453. 453 img : @types.Image,
  454. 454) -> IlluminationConsistencyResult {
  455. 455● let w = img.width
  456. 456 let h = img.height
  457. 457
  458. 458 // 计算梯度方向直方图
  459. 459 let mut direction_sum = 0.0
  460. 460 let mut direction_count = 0
  461. 461 let mut highlight_sum = 0.0
  462. 462 let mut highlight_count = 0
  463. 463 let mut shadow_sum = 0.0
  464. 464 let mut shadow_count = 0
  465. 465
  466. 466 let grad_threshold = 30.0
  467. 467
  468. 468 for y in 1..<(h - 1) {
  469. 469● for x in 1..<(w - 1) {
  470. 470● let idx = y * w + x
  471. 471● let gx = img.data[idx + 1].to_double() - img.data[idx - 1].to_double()
  472. 472● let gy = img.data[idx + w].to_double() - img.data[idx - w].to_double()
  473. 473● let magnitude = (gx * gx + gy * gy).sqrt()
  474. 474
  475. 475 if magnitude > grad_threshold {
  476. 476● let angle = @math.atan2(gy, gx)
  477. 477 direction_sum += angle
  478. 478 direction_count += 1
  479. 479 }
  480. 480
  481. 481● let val = img.data[idx].to_double()
  482. 482 if val > 200.0 {
  483. 483● highlight_sum += val
  484. 484 highlight_count += 1
  485. 485 }
  486. 486 if val < 50.0 {
  487. 487● shadow_sum += val
  488. 488 shadow_count += 1
  489. 489 }
  490. 490 }
  491. 491 }
  492. 492
  493. 493 let illumination_direction = if direction_count > 0 {
  494. 494● direction_sum / direction_count.to_double()
  495. 495 } else {
  496. 496● 0.0
  497. 497 }
  498. 498
  499. 499 let highlight_distribution = if highlight_count > 0 {
  500. 500● highlight_sum / highlight_count.to_double()
  501. 501 } else {
  502. 502● 0.0
  503. 503 }
  504. 504
  505. 505 let shadow_consistency = if shadow_count > 0 {
  506. 506● shadow_sum / shadow_count.to_double()
  507. 507 } else {
  508. 508● 0.0
  509. 509 }
  510. 510
  511. 511 // 光照不一致性:高光和阴影分布的差异
  512. 512● let illumination_inconsistency = (highlight_distribution - shadow_consistency).abs() /
  513. 513 255.0
  514. 514
  515. 515 IlluminationConsistencyResult::{
  516. 516 illumination_direction,
  517. 517 shadow_consistency: shadow_consistency / 255.0,
  518. 518 highlight_distribution: highlight_distribution / 255.0,
  519. 519 illumination_inconsistency,
  520. 520 has_inconsistent_lighting: illumination_inconsistency > 0.5,
  521. 521 }
  522. 522}
  523. 523
  524. 524///|
  525. 525/// 元数据取证分析
  526. 526/// 分析图像元数据一致性
  527. 527pub fn analyze_metadata_forensics(
  528. 528 img : @types.Image,
  529. 529) -> MetadataForensicsResult {
  530. 530● let w = img.width
  531. 531 let h = img.height
  532. 532 let total = w * h
  533. 533
  534. 534 // 基于图像特征推断元数据
  535. 535 let unique_values : Array[Int32] = []
  536. 536 for i in 0..<total {
  537. 537● let v = img.data[i].to_int()
  538. 538 let mut found = false
  539. 539● for j in 0..<unique_values.length() {
  540. 540● if unique_values[j] == v {
  541. 541● found = true
  542. 542 break
  543. 543 }
  544. 544 }
  545. 545 if !found {
  546. 546● unique_values.push(v)
  547. 547 }
  548. 548 }
  549. 549
  550. 550 // 软件签名推断
  551. 551● let software = if unique_values.length() < 10 {
  552. 552● "Paint/Editor"
  553. 553● } else if unique_values.length() < 100 {
  554. 554● "JPEG/Compressed"
  555. 555 } else {
  556. 556● "Camera/Raw"
  557. 557 }
  558. 558
  559. 559 // 创建时间推断(基于图像尺寸特征)
  560. 560 let creation_time = if w * h < 10000 {
  561. 561● "Early/Low-res"
  562. 562● } else if w * h < 1000000 {
  563. 563● "Standard"
  564. 564 } else {
  565. 565○ "Modern/High-res"
  566. 566 }
  567. 567
  568. 568 // 设备信息推断
  569. 569 let device = if w == h {
  570. 570● "Square/Social"
  571. 571● } else if w > h * 2 {
  572. 572● "Panorama"
  573. 573● } else if h > w * 2 {
  574. 574● "Portrait/Mobile"
  575. 575 } else {
  576. 576○ "Standard/Camera"
  577. 577 }
  578. 578
  579. 579 // 一致性评分
  580. 580● let consistency = if unique_values.length() > 50 && w > 64 && h > 64 {
  581. 581● 0.8
  582. 582● } else if unique_values.length() > 10 {
  583. 583● 0.6
  584. 584 } else {
  585. 585● 0.3
  586. 586 }
  587. 587
  588. 588 let has_inconsistency = consistency < 0.5
  589. 589
  590. 590 MetadataForensicsResult::{
  591. 591 has_metadata: true,
  592. 592 software_signature: software,
  593. 593 creation_time,
  594. 594 device_info: device,
  595. 595 metadata_consistency: consistency,
  596. 596 has_inconsistency,
  597. 597 }
  598. 598}
  599. 599
  600. 600///|
  601. 601/// JPEG ghost 分析
  602. 602/// 检测 JPEG 压缩历史中的 ghost 区域
  603. 603pub fn analyze_jpeg_ghost(img : @types.Image) -> JpegGhostResult {
  604. 604● let w = img.width
  605. 605 let h = img.height
  606. 606 let total = w * h
  607. 607
  608. 608 // 模拟不同质量级别的重压缩差异
  609. 609 let quality_levels = [50, 60, 70, 80, 90]
  610. 610 let mut ghost_count = 0
  611. 611 let mut primary_quality = 0
  612. 612 let mut secondary_quality = 0
  613. 613 let mut prev_diff = 0.0
  614. 614
  615. 615● for qi in 0..<quality_levels.length() {
  616. 616● let q = quality_levels[qi]
  617. 617 let quant = 256 / (q + 1)
  618. 618 if quant == 0 {
  619. 619○ continue
  620. 620 }
  621. 621 let mut diff_sum = 0.0
  622. 622 for i in 0..<total {
  623. 623● let val = img.data[i].to_int()
  624. 624 let quantized = val / quant * quant
  625. 625 let clamped = if quantized < 0 {
  626. 626○ 0
  627. 627● } else if quantized > 255 {
  628. 628○ 255
  629. 629 } else {
  630. 630● quantized
  631. 631 }
  632. 632● diff_sum += (val - clamped).to_double().abs()
  633. 633 }
  634. 634● let avg_diff = diff_sum / total.to_double()
  635. 635
  636. 636 // ghost 检测:差异变化非单调
  637. 637 if qi > 0 && avg_diff > prev_diff * 1.2 {
  638. 638● ghost_count += 1
  639. 639 if primary_quality == 0 {
  640. 640● primary_quality = quality_levels[qi - 1]
  641. 641 secondary_quality = q
  642. 642 }
  643. 643 }
  644. 644 prev_diff = avg_diff
  645. 645 }
  646. 646
  647. 647 JpegGhostResult::{
  648. 648 ghost_quality_levels: quality_levels,
  649. 649 ghost_region_count: ghost_count,
  650. 650 has_ghost: ghost_count > 0,
  651. 651 primary_quality,
  652. 652 secondary_quality,
  653. 653 }
  654. 654}
  655. 655
  656. 656///|
  657. 657/// CFA(颜色滤波阵列)分析
  658. 658/// 检测 Bayer 模式一致性
  659. 659pub fn analyze_cfa_pattern(img : @types.Image) -> CfaAnalysisResult {
  660. 660● let w = img.width
  661. 661 let h = img.height
  662. 662
  663. 663 // 分析像素值交替模式(Bayer 模式特征)
  664. 664 let mut bayer_score = 0.0
  665. 665 let mut artifact_score = 0.0
  666. 666 let mut count = 0
  667. 667
  668. 668 for y in 0..<(h - 1) {
  669. 669● for x in 0..<(w - 1) {
  670. 670● let idx = y * w + x
  671. 671● let v00 = img.data[idx].to_double()
  672. 672● let v01 = img.data[idx + 1].to_double()
  673. 673● let v10 = img.data[idx + w].to_double()
  674. 674● let v11 = img.data[idx + w + 1].to_double()
  675. 675
  676. 676 // Bayer 模式:对角像素相似,相邻像素差异大
  677. 677● let diag_diff = (v00 - v11).abs()
  678. 678● let adj_diff = (v00 - v01).abs() + (v00 - v10).abs()
  679. 679
  680. 680 if adj_diff > 0 {
  681. 681● bayer_score += diag_diff / adj_diff
  682. 682 }
  683. 683
  684. 684 // CFA 伪影:插值痕迹
  685. 685 let interpolated = (v00 + v01 + v10 + v11) / 4.0
  686. 686● artifact_score += (v00 - interpolated).abs()
  687. 687 count += 1
  688. 688 }
  689. 689 }
  690. 690
  691. 691 if count > 0 {
  692. 692● bayer_score /= count.to_double()
  693. 693● artifact_score /= count.to_double()
  694. 694 }
  695. 695 artifact_score /= 255.0
  696. 696
  697. 697 let pattern = if bayer_score < 0.3 {
  698. 698● "Bayer/RGGB"
  699. 699● } else if bayer_score < 0.6 {
  700. 700○ "Unknown/Mixed"
  701. 701 } else {
  702. 702● "Non-CFA/Processed"
  703. 703 }
  704. 704
  705. 705 let is_consistent = bayer_score < 0.4 && artifact_score < 0.2
  706. 706
  707. 707 CfaAnalysisResult::{
  708. 708 cfa_pattern: pattern,
  709. 709 bayer_pattern_score: bayer_score,
  710. 710 cfa_artifact_level: artifact_score,
  711. 711 is_cfa_consistent: is_consistent,
  712. 712 }
  713. 713}
  714. 714
  715. 715///|
  716. 716/// 综合篡改检测
  717. 717/// 融合多种取证分析结果,给出综合篡改判定
  718. 718pub fn detect_tamper_comprehensive(
  719. 719 img : @types.Image,
  720. 720 ela_quality : Int32,
  721. 721) -> TamperDetectionResult raise @types.LoadError {
  722. 722● let ela = analyze_ela(img, ela_quality)
  723. 723● let noise = analyze_noise_residual(img)
  724. 724● let dct = analyze_dct_coefficients(img)
  725. 725● let illumination = analyze_illumination_consistency(img)
  726. 726● let metadata = analyze_metadata_forensics(img)
  727. 727● let jpeg_ghost = analyze_jpeg_ghost(img)
  728. 728● let cfa = analyze_cfa_pattern(img)
  729. 729
  730. 730 // 各指标评分
  731. 731 let ela_score = if ela.tampered_region_ratio > 0.1 {
  732. 732● 0.8
  733. 733● } else if ela.tampered_region_ratio > 0.05 {
  734. 734○ 0.5
  735. 735 } else {
  736. 736● 0.2
  737. 737 }
  738. 738
  739. 739● let noise_score = if noise.pattern_consistency < 0.5 { 0.7 } else { 0.3 }
  740. 740
  741. 741◐ let dct_score = if dct.double_jpeg_indicator > 0.3 { 0.6 } else { 0.3 }
  742. 742
  743. 743 let illum_score = if illumination.has_inconsistent_lighting {
  744. 744● 0.8
  745. 745 } else {
  746. 746● 0.2
  747. 747 }
  748. 748
  749. 749● let ghost_score = if jpeg_ghost.has_ghost { 0.7 } else { 0.2 }
  750. 750
  751. 751● let cfa_score = if !cfa.is_cfa_consistent { 0.6 } else { 0.2 }
  752. 752
  753. 753● let meta_score = if metadata.has_inconsistency { 0.7 } else { 0.3 }
  754. 754
  755. 755 // 加权综合
  756. 756 let tamper_prob = ela_score * 0.25 +
  757. 757 noise_score * 0.15 +
  758. 758 dct_score * 0.15 +
  759. 759 illum_score * 0.15 +
  760. 760 ghost_score * 0.10 +
  761. 761 cfa_score * 0.10 +
  762. 762 meta_score * 0.10
  763. 763
  764. 764 let is_tampered = tamper_prob > 0.5
  765. 765
  766. 766 let tamper_type = if ela_score > 0.5 && illum_score > 0.5 {
  767. 767● "内容篡改+光照不一致"
  768. 768● } else if dct_score > 0.5 && ghost_score > 0.5 {
  769. 769○ "双JPEG压缩痕迹"
  770. 770● } else if noise_score > 0.5 {
  771. 771● "噪声模式异常"
  772. 772● } else if cfa_score > 0.5 {
  773. 773● "CFA模式不一致"
  774. 774○ } else if meta_score > 0.5 {
  775. 775○ "元数据不一致"
  776. 776○ } else if is_tampered {
  777. 777○ "综合篡改迹象"
  778. 778 } else {
  779. 779○ "未检测到明显篡改"
  780. 780 }
  781. 781
  782. 782● let confidence = (tamper_prob - 0.5).abs() * 2.0
  783. 783
  784. 784 let details = "ELA=" +
  785. 785● ela_score.to_string() +
  786. 786 ", Noise=" +
  787. 787● noise_score.to_string() +
  788. 788 ", DCT=" +
  789. 789● dct_score.to_string() +
  790. 790 ", Illum=" +
  791. 791● illum_score.to_string() +
  792. 792 ", Ghost=" +
  793. 793● ghost_score.to_string() +
  794. 794 ", CFA=" +
  795. 795● cfa_score.to_string() +
  796. 796 ", Meta=" +
  797. 797● meta_score.to_string()
  798. 798
  799. 799 // 篡改区域(简化:返回整图区域)
  800. 800 let tampered_regions : Array[(Int32, Int32, Int32, Int32)] = []
  801. 801 if is_tampered {
  802. 802● tampered_regions.push((0, 0, img.width, img.height))
  803. 803 }
  804. 804
  805. 805 TamperDetectionResult::{
  806. 806 is_tampered,
  807. 807 tamper_probability: tamper_prob,
  808. 808 tamper_type,
  809. 809 tampered_regions,
  810. 810 confidence,
  811. 811 analysis_details: details,
  812. 812 }
  813. 813}