image.vision\face_recognition\face_recognition_system.mbt

91.3% · 209 / 229 points · 948 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/// # 人脸识别系统 face_recognition/face_recognition_system
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 人脸识别与表情识别(v33.0.0)
  7. 7// 人脸检测、人脸对齐、特征提取、人脸识别、表情识别、年龄性别估计
  8. 8
  9. 9///|
  10. 10/// 人脸检测算法类型
  11. 11/// `#non_exhaustive` 表示未来可能添加新构造器
  12. 12#derive(Eq, @debug.Debug)
  13. 13#non_exhaustive
  14. 14pub(all) enum FaceDetectionAlgorithm {
  15. 15 HaarCascade
  16. 16 HOG_SVM
  17. 17 MTCNN
  18. 18 RetinaFace
  19. 19 YOLOFace
  20. 20 BlazeFace
  21. 21 FaceBoxes
  22. 22 Unknown
  23. 23}
  24. 24
  25. 25///|
  26. 26pub extend FaceDetectionAlgorithm with @debug.Debug::{to_repr}
  27. 27
  28. 28///|
  29. 29pub extend FaceDetectionAlgorithm with Eq::{not_equal, equal}
  30. 30
  31. 31///|
  32. 32/// 人脸识别算法类型
  33. 33/// `#non_exhaustive` 表示未来可能添加新构造器
  34. 34#derive(Eq, @debug.Debug)
  35. 35#non_exhaustive
  36. 36pub(all) enum FaceRecognitionAlgorithm {
  37. 37 FaceNet
  38. 38 ArcFace
  39. 39 CosFace
  40. 40 SphereFace
  41. 41 DeepFace
  42. 42 VGGFace
  43. 43 InsightFace
  44. 44 Unknown
  45. 45}
  46. 46
  47. 47///|
  48. 48pub extend FaceRecognitionAlgorithm with @debug.Debug::{to_repr}
  49. 49
  50. 50///|
  51. 51pub extend FaceRecognitionAlgorithm with Eq::{not_equal, equal}
  52. 52
  53. 53///|
  54. 54/// 表情类型
  55. 55/// `#non_exhaustive` 表示未来可能添加新构造器
  56. 56#derive(Eq, @debug.Debug)
  57. 57#non_exhaustive
  58. 58pub(all) enum ExpressionType {
  59. 59 Neutral
  60. 60 Happy
  61. 61 Sad
  62. 62 Angry
  63. 63 Surprise
  64. 64 Fear
  65. 65 Disgust
  66. 66 Contempt
  67. 67 Unknown
  68. 68}
  69. 69
  70. 70///|
  71. 71pub extend ExpressionType with @debug.Debug::{to_repr}
  72. 72
  73. 73///|
  74. 74pub extend ExpressionType with Eq::{not_equal, equal}
  75. 75
  76. 76///|
  77. 77/// 人脸检测结果
  78. 78#derive(Eq, @debug.Debug)
  79. 79pub(all) struct FaceDetectionResult {
  80. 80 bounding_box : Array[Double]
  81. 81 confidence : Double
  82. 82 landmarks : Array[Array[Double]]
  83. 83 num_landmarks : Int32
  84. 84 face_id : Int32
  85. 85 is_frontal : Bool
  86. 86 yaw : Double
  87. 87 pitch : Double
  88. 88 roll : Double
  89. 89}
  90. 90
  91. 91///|
  92. 92pub extend FaceDetectionResult with Eq::{not_equal, equal}
  93. 93
  94. 94///|
  95. 95pub extend FaceDetectionResult with @debug.Debug::{to_repr}
  96. 96
  97. 97///|
  98. 98/// 人脸特征向量
  99. 99#derive(Eq, @debug.Debug)
  100. 100pub(all) struct FaceFeature {
  101. 101 vector : Array[Double]
  102. 102 dimension : Int32
  103. 103 norm : Double
  104. 104 is_normalized : Bool
  105. 105}
  106. 106
  107. 107///|
  108. 108pub extend FaceFeature with Eq::{not_equal, equal}
  109. 109
  110. 110///|
  111. 111pub extend FaceFeature with @debug.Debug::{to_repr}
  112. 112
  113. 113///|
  114. 114/// 人脸识别结果
  115. 115#derive(Eq, @debug.Debug)
  116. 116pub(all) struct FaceRecognitionResult {
  117. 117 face_id : Int32
  118. 118 identity : String
  119. 119 confidence : Double
  120. 120 similarity : Double
  121. 121 is_known : Bool
  122. 122 matched_face_id : Int32
  123. 123 bounding_box : Array[Double]
  124. 124}
  125. 125
  126. 126///|
  127. 127pub extend FaceRecognitionResult with Eq::{not_equal, equal}
  128. 128
  129. 129///|
  130. 130pub extend FaceRecognitionResult with @debug.Debug::{to_repr}
  131. 131
  132. 132///|
  133. 133/// 表情识别结果
  134. 134#derive(Eq, @debug.Debug)
  135. 135pub(all) struct ExpressionRecognitionResult {
  136. 136 expression : ExpressionType
  137. 137 confidence : Double
  138. 138 probabilities : Array[Double]
  139. 139 num_classes : Int32
  140. 140 dominant_expression : String
  141. 141}
  142. 142
  143. 143///|
  144. 144pub extend ExpressionRecognitionResult with Eq::{not_equal, equal}
  145. 145
  146. 146///|
  147. 147pub extend ExpressionRecognitionResult with @debug.Debug::{to_repr}
  148. 148
  149. 149///|
  150. 150/// 年龄性别估计结果
  151. 151#derive(Eq, @debug.Debug)
  152. 152pub(all) struct AgeGenderEstimationResult {
  153. 153 age : Double
  154. 154 age_range : Array[Double]
  155. 155 gender : String
  156. 156 gender_confidence : Double
  157. 157 is_male : Bool
  158. 158}
  159. 159
  160. 160///|
  161. 161pub extend AgeGenderEstimationResult with Eq::{not_equal, equal}
  162. 162
  163. 163///|
  164. 164pub extend AgeGenderEstimationResult with @debug.Debug::{to_repr}
  165. 165
  166. 166///|
  167. 167/// 人脸属性分析结果
  168. 168#derive(Eq, @debug.Debug)
  169. 169pub(all) struct FaceAttributeAnalysis {
  170. 170 detection : FaceDetectionResult
  171. 171 recognition : FaceRecognitionResult
  172. 172 expression : ExpressionRecognitionResult
  173. 173 age_gender : AgeGenderEstimationResult
  174. 174 face_quality : Double
  175. 175 brightness : Double
  176. 176 sharpness : Double
  177. 177 occlusion_rate : Double
  178. 178}
  179. 179
  180. 180///|
  181. 181pub extend FaceAttributeAnalysis with Eq::{not_equal, equal}
  182. 182
  183. 183///|
  184. 184pub extend FaceAttributeAnalysis with @debug.Debug::{to_repr}
  185. 185
  186. 186///|
  187. 187/// 人脸库
  188. 188#derive(Eq, @debug.Debug)
  189. 189pub(all) struct FaceDatabase {
  190. 190 faces : Array[FaceFeature]
  191. 191 identities : Array[String]
  192. 192 num_faces : Int32
  193. 193 threshold : Double
  194. 194 algorithm : FaceRecognitionAlgorithm
  195. 195}
  196. 196
  197. 197///|
  198. 198pub extend FaceDatabase with Eq::{not_equal, equal}
  199. 199
  200. 200///|
  201. 201pub extend FaceDatabase with @debug.Debug::{to_repr}
  202. 202
  203. 203///|
  204. 204/// 人脸识别配置
  205. 205#derive(Eq, @debug.Debug)
  206. 206pub(all) struct FaceRecognitionConfig {
  207. 207 detection_algorithm : FaceDetectionAlgorithm
  208. 208 recognition_algorithm : FaceRecognitionAlgorithm
  209. 209 detection_threshold : Double
  210. 210 recognition_threshold : Double
  211. 211 min_face_size : Int32
  212. 212 max_num_faces : Int32
  213. 213 use_landmarks : Bool
  214. 214 use_alignment : Bool
  215. 215 feature_dimension : Int32
  216. 216}
  217. 217
  218. 218///|
  219. 219pub extend FaceRecognitionConfig with Eq::{not_equal, equal}
  220. 220
  221. 221///|
  222. 222pub extend FaceRecognitionConfig with @debug.Debug::{to_repr}
  223. 223
  224. 224///|
  225. 225/// 创建默认人脸识别配置
  226. 226pub fn create_default_face_config() -> FaceRecognitionConfig {
  227. 227● FaceRecognitionConfig::{
  228. 228 detection_algorithm: FaceDetectionAlgorithm::MTCNN,
  229. 229 recognition_algorithm: FaceRecognitionAlgorithm::ArcFace,
  230. 230 detection_threshold: 0.7,
  231. 231 recognition_threshold: 0.5,
  232. 232 min_face_size: 40,
  233. 233 max_num_faces: 10,
  234. 234 use_landmarks: true,
  235. 235 use_alignment: true,
  236. 236 feature_dimension: 512,
  237. 237 }
  238. 238}
  239. 239
  240. 240///|
  241. 241/// 创建空的人脸库
  242. 242pub fn create_face_database(
  243. 243 algorithm : FaceRecognitionAlgorithm,
  244. 244 threshold : Double,
  245. 245) -> FaceDatabase {
  246. 246● FaceDatabase::{
  247. 247 faces: [],
  248. 248 identities: [],
  249. 249 num_faces: 0,
  250. 250 threshold,
  251. 251 algorithm,
  252. 252 }
  253. 253}
  254. 254
  255. 255///|
  256. 256/// 检测人脸(简化版:基于肤色和图像特征的启发式检测)
  257. 257pub fn detect_faces(
  258. 258 img : @types.Image,
  259. 259 config : FaceRecognitionConfig,
  260. 260) -> Array[FaceDetectionResult] raise @types.LoadError {
  261. 261● ignore(config)
  262. 262 // 输入验证
  263. 263 if img.width <= 0 || img.height <= 0 {
  264. 264● raise @types.LoadError::DecodeFailed(
  265. 265 "detect_faces: 图像尺寸必须大于0",
  266. 266 )
  267. 267 }
  268. 268 if img.channels < 1 || img.channels > 4 {
  269. 269● raise @types.LoadError::DecodeFailed(
  270. 270 "detect_faces: 通道数必须在1-4之间",
  271. 271 )
  272. 272 }
  273. 273 let expected_size = img.width * img.height * img.channels
  274. 274● if img.data.length() != expected_size {
  275. 275● raise @types.LoadError::DecodeFailed("detect_faces: 数据大小不匹配")
  276. 276 }
  277. 277 let w = img.width
  278. 278 let h = img.height
  279. 279 let faces : Array[FaceDetectionResult] = []
  280. 280
  281. 281 // 简化版:检测图像中的高对比度区域作为人脸
  282. 282 // 实际实现应该使用深度学习模型或 Haar 级联分类器
  283. 283
  284. 284 // 计算图像梯度,寻找类人脸区域
  285. 285 let mut max_response = 0.0
  286. 286● let mut center_x = w.to_double() / 2.0
  287. 287● let mut center_y = h.to_double() / 2.0
  288. 288
  289. 289 let block_size = 32
  290. 290 for by in 0..<(h / block_size) {
  291. 291● for bx in 0..<(w / block_size) {
  292. 292● let mut response = 0.0
  293. 293 for y in 0..<block_size {
  294. 294● for x in 0..<block_size {
  295. 295● let px = bx * block_size + x
  296. 296 let py = by * block_size + y
  297. 297 if px > 0 && px < w - 1 && py > 0 && py < h - 1 {
  298. 298● let idx = py * w + px
  299. 299● let gx = img.data[idx + 1].to_double() -
  300. 300● img.data[idx - 1].to_double()
  301. 301● let gy = img.data[idx + w].to_double() -
  302. 302● img.data[idx - w].to_double()
  303. 303● response += (gx * gx + gy * gy).sqrt()
  304. 304 }
  305. 305 }
  306. 306 }
  307. 307● response /= (block_size * block_size).to_double()
  308. 308 if response > max_response {
  309. 309● max_response = response
  310. 310● center_x = (bx * block_size + block_size / 2).to_double()
  311. 311● center_y = (by * block_size + block_size / 2).to_double()
  312. 312 }
  313. 313 }
  314. 314 }
  315. 315
  316. 316 // 生成简化的人脸检测结果
  317. 317 let face_width = 100.0
  318. 318 let face_height = 120.0
  319. 319 let bounding_box = [
  320. 320 center_x - face_width / 2.0,
  321. 321 center_y - face_height / 2.0,
  322. 322 face_width,
  323. 323 face_height,
  324. 324 ]
  325. 325
  326. 326 // 5 个关键点(双眼、鼻尖、嘴角)
  327. 327 let landmarks : Array[Array[Double]] = []
  328. 328● landmarks.push([center_x - 20.0, center_y - 20.0]) // 左眼
  329. 329● landmarks.push([center_x + 20.0, center_y - 20.0]) // 右眼
  330. 330● landmarks.push([center_x, center_y]) // 鼻尖
  331. 331● landmarks.push([center_x - 15.0, center_y + 25.0]) // 左嘴角
  332. 332● landmarks.push([center_x + 15.0, center_y + 25.0]) // 右嘴角
  333. 333
  334. 334 let face = FaceDetectionResult::{
  335. 335 bounding_box,
  336. 336 confidence: 0.75,
  337. 337 landmarks,
  338. 338 num_landmarks: 5,
  339. 339 face_id: 0,
  340. 340 is_frontal: true,
  341. 341 yaw: 0.0,
  342. 342 pitch: 0.0,
  343. 343 roll: 0.0,
  344. 344 }
  345. 345
  346. 346● faces.push(face)
  347. 347 faces
  348. 348}
  349. 349
  350. 350///|
  351. 351/// 提取人脸特征(简化版:基于图像统计特征)
  352. 352pub fn extract_face_feature(
  353. 353 img : @types.Image,
  354. 354 face : FaceDetectionResult,
  355. 355 config : FaceRecognitionConfig,
  356. 356) -> FaceFeature raise @types.LoadError {
  357. 357 // 输入验证
  358. 358● if img.width <= 0 || img.height <= 0 {
  359. 359● raise @types.LoadError::DecodeFailed(
  360. 360 "extract_face_feature: 图像尺寸必须大于0",
  361. 361 )
  362. 362 }
  363. 363 if img.channels < 1 || img.channels > 4 {
  364. 364● raise @types.LoadError::DecodeFailed(
  365. 365 "extract_face_feature: 通道数必须在1-4之间",
  366. 366 )
  367. 367 }
  368. 368 let expected_size = img.width * img.height * img.channels
  369. 369● if img.data.length() != expected_size {
  370. 370● raise @types.LoadError::DecodeFailed(
  371. 371 "extract_face_feature: 数据大小不匹配",
  372. 372 )
  373. 373 }
  374. 374 let w = img.width
  375. 375 let h = img.height
  376. 376 let dimension = config.feature_dimension
  377. 377 let vector : Array[Double] = []
  378. 378
  379. 379 // 简化版:使用人脸区域的图像统计特征作为特征向量
  380. 380 // 实际实现应该使用深度学习模型(FaceNet/ArcFace 等)
  381. 381
  382. 382● let bx = face.bounding_box[0].to_int()
  383. 383● let by = face.bounding_box[1].to_int()
  384. 384● let bw = face.bounding_box[2].to_int()
  385. 385● let bh = face.bounding_box[3].to_int()
  386. 386
  387. 387 // 计算人脸区域的统计特征
  388. 388 let mut sum = 0.0
  389. 389 let mut sum_sq = 0.0
  390. 390 let mut count = 0
  391. 391 for y in 0..<bh {
  392. 392● for x in 0..<bw {
  393. 393● let px = bx + x
  394. 394 let py = by + y
  395. 395 if px >= 0 && px < w && py >= 0 && py < h {
  396. 396● let pixel = img.data[py * w + px].to_double()
  397. 397 sum += pixel
  398. 398 sum_sq += pixel * pixel
  399. 399 count += 1
  400. 400 }
  401. 401 }
  402. 402 }
  403. 403
  404. 404● let mean = if count > 0 { sum / count.to_double() } else { 0.0 }
  405. 405 let variance = if count > 0 {
  406. 406● sum_sq / count.to_double() - mean * mean
  407. 407 } else {
  408. 408● 0.0
  409. 409 }
  410. 410● let std_dev = if variance > 0.0 { variance.sqrt() } else { 0.0 }
  411. 411
  412. 412 // 生成特征向量(简化版:用统计特征填充)
  413. 413 for i in 0..<dimension {
  414. 414● let value = mean * 0.01 + std_dev * 0.001 + (i % 10).to_double() * 0.001
  415. 415● vector.push(value)
  416. 416 }
  417. 417
  418. 418 // 计算 L2 范数
  419. 419 let mut norm_sq = 0.0
  420. 420 for v in vector {
  421. 421● norm_sq += v * v
  422. 422 }
  423. 423◐ let norm = if norm_sq > 0.0 { norm_sq.sqrt() } else { 1.0 }
  424. 424
  425. 425 FaceFeature::{ vector, dimension, norm, is_normalized: false, }
  426. 426}
  427. 427
  428. 428///|
  429. 429/// 计算余弦相似度
  430. 430pub fn calculate_cosine_similarity(
  431. 431 feat1 : FaceFeature,
  432. 432 feat2 : FaceFeature,
  433. 433) -> Double {
  434. 434● if feat1.dimension != feat2.dimension {
  435. 435● return 0.0
  436. 436 }
  437. 437
  438. 438 let mut dot = 0.0
  439. 439 for i in 0..<feat1.dimension {
  440. 440● dot += feat1.vector[i] * feat2.vector[i]
  441. 441 }
  442. 442
  443. 443 if feat1.norm > 0.0 && feat2.norm > 0.0 {
  444. 444● dot / (feat1.norm * feat2.norm)
  445. 445 } else {
  446. 446● 0.0
  447. 447 }
  448. 448}
  449. 449
  450. 450///|
  451. 451/// 向人脸库添加人脸
  452. 452pub fn add_face_to_database(
  453. 453 database : FaceDatabase,
  454. 454 feature : FaceFeature,
  455. 455 identity : String,
  456. 456) -> FaceDatabase {
  457. 457● let new_faces = database.faces
  458. 458● new_faces.push(feature)
  459. 459 let new_identities = database.identities
  460. 460● new_identities.push(identity)
  461. 461
  462. 462 FaceDatabase::{
  463. 463 faces: new_faces,
  464. 464 identities: new_identities,
  465. 465 num_faces: database.num_faces + 1,
  466. 466 threshold: database.threshold,
  467. 467 algorithm: database.algorithm,
  468. 468 }
  469. 469}
  470. 470
  471. 471///|
  472. 472/// 在人脸库中识别人脸
  473. 473pub fn recognize_face_in_database(
  474. 474 database : FaceDatabase,
  475. 475 feature : FaceFeature,
  476. 476 bounding_box : Array[Double],
  477. 477) -> FaceRecognitionResult {
  478. 478● let mut best_similarity = 0.0
  479. 479 let mut best_index = -1
  480. 480
  481. 481 for i in 0..<database.num_faces {
  482. 482● let similarity = calculate_cosine_similarity(feature, database.faces[i])
  483. 483 if similarity > best_similarity {
  484. 484● best_similarity = similarity
  485. 485 best_index = i
  486. 486 }
  487. 487 }
  488. 488
  489. 489 if best_index >= 0 && best_similarity >= database.threshold {
  490. 490● FaceRecognitionResult::{
  491. 491 face_id: 0,
  492. 492 identity: database.identities[best_index],
  493. 493 confidence: best_similarity,
  494. 494 similarity: best_similarity,
  495. 495 is_known: true,
  496. 496 matched_face_id: best_index,
  497. 497 bounding_box,
  498. 498 }
  499. 499 } else {
  500. 500● FaceRecognitionResult::{
  501. 501 face_id: 0,
  502. 502 identity: "unknown",
  503. 503 confidence: if best_similarity > 0.0 {
  504. 504● best_similarity
  505. 505 } else {
  506. 506● 0.0
  507. 507 },
  508. 508 similarity: best_similarity,
  509. 509 is_known: false,
  510. 510 matched_face_id: -1,
  511. 511 bounding_box,
  512. 512 }
  513. 513 }
  514. 514}
  515. 515
  516. 516///|
  517. 517/// 识别表情(简化版:基于人脸区域的图像特征)
  518. 518pub fn recognize_expression(
  519. 519 img : @types.Image,
  520. 520 face : FaceDetectionResult,
  521. 521) -> ExpressionRecognitionResult raise @types.LoadError {
  522. 522 // 输入验证
  523. 523● if img.width <= 0 || img.height <= 0 {
  524. 524● raise @types.LoadError::DecodeFailed(
  525. 525 "recognize_expression: 图像尺寸必须大于0",
  526. 526 )
  527. 527 }
  528. 528 if img.channels < 1 || img.channels > 4 {
  529. 529● raise @types.LoadError::DecodeFailed(
  530. 530 "recognize_expression: 通道数必须在1-4之间",
  531. 531 )
  532. 532 }
  533. 533 let expected_size = img.width * img.height * img.channels
  534. 534● if img.data.length() != expected_size {
  535. 535● raise @types.LoadError::DecodeFailed(
  536. 536 "recognize_expression: 数据大小不匹配",
  537. 537 )
  538. 538 }
  539. 539 let w = img.width
  540. 540 let h = img.height
  541. 541
  542. 542 // 简化版:基于人脸区域的亮度和对比度变化判断表情
  543. 543 // 实际实现应该使用深度学习模型
  544. 544
  545. 545● let bx = face.bounding_box[0].to_int()
  546. 546● let by = face.bounding_box[1].to_int()
  547. 547● let bw = face.bounding_box[2].to_int()
  548. 548● let bh = face.bounding_box[3].to_int()
  549. 549
  550. 550 // 计算嘴部区域的亮度变化(简化的表情判断)
  551. 551 let mouth_y = by + bh * 3 / 4
  552. 552 let mut mouth_brightness = 0.0
  553. 553 let mut count = 0
  554. 554 for y in mouth_y..<(mouth_y + bh / 4) {
  555. 555● for x in bx..<(bx + bw) {
  556. 556● if x >= 0 && x < w && y >= 0 && y < h {
  557. 557● mouth_brightness += img.data[y * w + x].to_double()
  558. 558 count += 1
  559. 559 }
  560. 560 }
  561. 561 }
  562. 562 mouth_brightness = if count > 0 {
  563. 563● mouth_brightness / count.to_double()
  564. 564 } else {
  565. 565○ 0.0
  566. 566 }
  567. 567
  568. 568 // 简化的表情分类
  569. 569 let mut expression = ExpressionType::Neutral
  570. 570 let mut confidence = 0.55
  571. 571 let probabilities : Array[Double] = []
  572. 572
  573. 573 if mouth_brightness > 150.0 {
  574. 574● expression = ExpressionType::Happy
  575. 575 confidence = 0.6
  576. 576● probabilities.push(0.1) // Neutral
  577. 577● probabilities.push(0.6) // Happy
  578. 578● probabilities.push(0.1) // Sad
  579. 579● probabilities.push(0.05) // Angry
  580. 580● probabilities.push(0.05) // Surprise
  581. 581● probabilities.push(0.05) // Fear
  582. 582● probabilities.push(0.03) // Disgust
  583. 583● probabilities.push(0.02) // Contempt
  584. 584● } else if mouth_brightness < 80.0 {
  585. 585● expression = ExpressionType::Sad
  586. 586 confidence = 0.5
  587. 587● probabilities.push(0.15)
  588. 588● probabilities.push(0.1)
  589. 589● probabilities.push(0.5)
  590. 590● probabilities.push(0.1)
  591. 591● probabilities.push(0.05)
  592. 592● probabilities.push(0.05)
  593. 593● probabilities.push(0.03)
  594. 594● probabilities.push(0.02)
  595. 595 } else {
  596. 596● expression = ExpressionType::Neutral
  597. 597 confidence = 0.55
  598. 598● probabilities.push(0.55)
  599. 599● probabilities.push(0.15)
  600. 600● probabilities.push(0.1)
  601. 601● probabilities.push(0.05)
  602. 602● probabilities.push(0.05)
  603. 603● probabilities.push(0.05)
  604. 604● probabilities.push(0.03)
  605. 605● probabilities.push(0.02)
  606. 606 }
  607. 607
  608. 608 let dominant_expression = if expression == ExpressionType::Neutral {
  609. 609● "neutral"
  610. 610● } else if expression == ExpressionType::Happy {
  611. 611● "happy"
  612. 612● } else if expression == ExpressionType::Sad {
  613. 613● "sad"
  614. 614○ } else if expression == ExpressionType::Angry {
  615. 615○ "angry"
  616. 616○ } else if expression == ExpressionType::Surprise {
  617. 617○ "surprise"
  618. 618○ } else if expression == ExpressionType::Fear {
  619. 619○ "fear"
  620. 620○ } else if expression == ExpressionType::Disgust {
  621. 621○ "disgust"
  622. 622○ } else if expression == ExpressionType::Contempt {
  623. 623○ "contempt"
  624. 624 } else {
  625. 625○ "unknown"
  626. 626 }
  627. 627
  628. 628 ExpressionRecognitionResult::{
  629. 629 expression,
  630. 630 confidence,
  631. 631 probabilities,
  632. 632 num_classes: 8,
  633. 633 dominant_expression,
  634. 634 }
  635. 635}
  636. 636
  637. 637///|
  638. 638/// 估计年龄和性别(简化版)
  639. 639pub fn estimate_age_gender(
  640. 640 img : @types.Image,
  641. 641 face : FaceDetectionResult,
  642. 642) -> AgeGenderEstimationResult raise @types.LoadError {
  643. 643 // 输入验证
  644. 644● if img.width <= 0 || img.height <= 0 {
  645. 645● raise @types.LoadError::DecodeFailed(
  646. 646 "estimate_age_gender: 图像尺寸必须大于0",
  647. 647 )
  648. 648 }
  649. 649 if img.channels < 1 || img.channels > 4 {
  650. 650● raise @types.LoadError::DecodeFailed(
  651. 651 "estimate_age_gender: 通道数必须在1-4之间",
  652. 652 )
  653. 653 }
  654. 654 let expected_size = img.width * img.height * img.channels
  655. 655● if img.data.length() != expected_size {
  656. 656● raise @types.LoadError::DecodeFailed(
  657. 657 "estimate_age_gender: 数据大小不匹配",
  658. 658 )
  659. 659 }
  660. 660 let w = img.width
  661. 661 let h = img.height
  662. 662
  663. 663 // 简化版:基于人脸区域的纹理和皱纹估计年龄
  664. 664 // 实际实现应该使用深度学习模型
  665. 665
  666. 666● let bx = face.bounding_box[0].to_int()
  667. 667● let by = face.bounding_box[1].to_int()
  668. 668● let bw = face.bounding_box[2].to_int()
  669. 669● let bh = face.bounding_box[3].to_int()
  670. 670
  671. 671 // 计算人脸区域的纹理复杂度(简化的年龄估计)
  672. 672 let mut texture_complexity = 0.0
  673. 673 let mut count = 0
  674. 674 for y in 1..<(bh - 1) {
  675. 675● for x in 1..<(bw - 1) {
  676. 676● let px = bx + x
  677. 677 let py = by + y
  678. 678 if px >= 1 && px < w - 1 && py >= 1 && py < h - 1 {
  679. 679● let idx = py * w + px
  680. 680● let gx = img.data[idx + 1].to_double() - img.data[idx - 1].to_double()
  681. 681● let gy = img.data[idx + w].to_double() - img.data[idx - w].to_double()
  682. 682● texture_complexity += (gx * gx + gy * gy).sqrt()
  683. 683 count += 1
  684. 684 }
  685. 685 }
  686. 686 }
  687. 687 texture_complexity = if count > 0 {
  688. 688● texture_complexity / count.to_double()
  689. 689 } else {
  690. 690○ 0.0
  691. 691 }
  692. 692
  693. 693 // 简化的年龄估计(纹理越复杂,年龄越大)
  694. 694 let age = 20.0 + texture_complexity * 2.0
  695. 695 let age_range = [age - 5.0, age + 5.0]
  696. 696
  697. 697 // 简化的性别判断(基于人脸区域的亮度和形状)
  698. 698 let is_male = texture_complexity > 10.0
  699. 699● let gender = if is_male { "male" } else { "female" }
  700. 700 let gender_confidence = 0.6
  701. 701
  702. 702 AgeGenderEstimationResult::{
  703. 703 age,
  704. 704 age_range,
  705. 705 gender,
  706. 706 gender_confidence,
  707. 707 is_male,
  708. 708 }
  709. 709}
  710. 710
  711. 711///|
  712. 712/// 评估人脸质量
  713. 713pub fn evaluate_face_quality(
  714. 714 img : @types.Image,
  715. 715 face : FaceDetectionResult,
  716. 716) -> Double raise @types.LoadError {
  717. 717 // 输入验证
  718. 718● if img.width <= 0 || img.height <= 0 {
  719. 719● raise @types.LoadError::DecodeFailed(
  720. 720 "evaluate_face_quality: 图像尺寸必须大于0",
  721. 721 )
  722. 722 }
  723. 723 if img.channels < 1 || img.channels > 4 {
  724. 724● raise @types.LoadError::DecodeFailed(
  725. 725 "evaluate_face_quality: 通道数必须在1-4之间",
  726. 726 )
  727. 727 }
  728. 728 let expected_size = img.width * img.height * img.channels
  729. 729● if img.data.length() != expected_size {
  730. 730● raise @types.LoadError::DecodeFailed(
  731. 731 "evaluate_face_quality: 数据大小不匹配",
  732. 732 )
  733. 733 }
  734. 734 let w = img.width
  735. 735 let h = img.height
  736. 736
  737. 737● let bx = face.bounding_box[0].to_int()
  738. 738● let by = face.bounding_box[1].to_int()
  739. 739● let bw = face.bounding_box[2].to_int()
  740. 740● let bh = face.bounding_box[3].to_int()
  741. 741
  742. 742 // 计算亮度
  743. 743 let mut brightness = 0.0
  744. 744 let mut sharpness = 0.0
  745. 745 let mut count = 0
  746. 746 for y in 1..<(bh - 1) {
  747. 747● for x in 1..<(bw - 1) {
  748. 748● let px = bx + x
  749. 749 let py = by + y
  750. 750 if px >= 1 && px < w - 1 && py >= 1 && py < h - 1 {
  751. 751● let idx = py * w + px
  752. 752● brightness += img.data[idx].to_double()
  753. 753● let gx = img.data[idx + 1].to_double() - img.data[idx - 1].to_double()
  754. 754● let gy = img.data[idx + w].to_double() - img.data[idx - w].to_double()
  755. 755● sharpness += (gx * gx + gy * gy).sqrt()
  756. 756 count += 1
  757. 757 }
  758. 758 }
  759. 759 }
  760. 760
  761. 761◐ brightness = if count > 0 { brightness / count.to_double() } else { 0.0 }
  762. 762◐ sharpness = if count > 0 { sharpness / count.to_double() } else { 0.0 }
  763. 763
  764. 764 // 综合质量评分(亮度 40% + 锐度 60%)
  765. 765 let brightness_score = if brightness > 80.0 && brightness < 180.0 {
  766. 766● 1.0
  767. 767 } else {
  768. 768○ 0.5
  769. 769 }
  770. 770 let sharpness_score = if sharpness > 20.0 {
  771. 771● 1.0
  772. 772● } else if sharpness > 10.0 {
  773. 773○ 0.7
  774. 774 } else {
  775. 775● 0.4
  776. 776 }
  777. 777
  778. 778 brightness_score * 0.4 + sharpness_score * 0.6
  779. 779}
  780. 780
  781. 781///|
  782. 782/// 完整的人脸属性分析
  783. 783pub fn analyze_face_attributes(
  784. 784 img : @types.Image,
  785. 785 face : FaceDetectionResult,
  786. 786 database : FaceDatabase,
  787. 787 config : FaceRecognitionConfig,
  788. 788) -> FaceAttributeAnalysis raise @types.LoadError {
  789. 789 // 输入验证
  790. 790● if img.width <= 0 || img.height <= 0 {
  791. 791● raise @types.LoadError::DecodeFailed(
  792. 792 "analyze_face_attributes: 图像尺寸必须大于0",
  793. 793 )
  794. 794 }
  795. 795 if img.channels < 1 || img.channels > 4 {
  796. 796● raise @types.LoadError::DecodeFailed(
  797. 797 "analyze_face_attributes: 通道数必须在1-4之间",
  798. 798 )
  799. 799 }
  800. 800 let expected_size = img.width * img.height * img.channels
  801. 801● if img.data.length() != expected_size {
  802. 802● raise @types.LoadError::DecodeFailed(
  803. 803 "analyze_face_attributes: 数据大小不匹配",
  804. 804 )
  805. 805 }
  806. 806● let feature = extract_face_feature(img, face, config)
  807. 807● let recognition = recognize_face_in_database(
  808. 808 database,
  809. 809 feature,
  810. 810 face.bounding_box,
  811. 811 )
  812. 812● let expression = recognize_expression(img, face)
  813. 813● let age_gender = estimate_age_gender(img, face)
  814. 814● let quality = evaluate_face_quality(img, face)
  815. 815
  816. 816 // 计算亮度和锐度
  817. 817 let w = img.width
  818. 818 let h = img.height
  819. 819● let bx = face.bounding_box[0].to_int()
  820. 820● let by = face.bounding_box[1].to_int()
  821. 821● let bw = face.bounding_box[2].to_int()
  822. 822● let bh = face.bounding_box[3].to_int()
  823. 823
  824. 824 let mut brightness = 0.0
  825. 825 let mut sharpness = 0.0
  826. 826 let mut count = 0
  827. 827 for y in 0..<bh {
  828. 828● for x in 0..<bw {
  829. 829● let px = bx + x
  830. 830 let py = by + y
  831. 831 if px >= 0 && px < w && py >= 0 && py < h {
  832. 832● brightness += img.data[py * w + px].to_double()
  833. 833 count += 1
  834. 834 }
  835. 835 }
  836. 836 }
  837. 837◐ brightness = if count > 0 { brightness / count.to_double() } else { 0.0 }
  838. 838 sharpness = quality * 50.0
  839. 839
  840. 840 FaceAttributeAnalysis::{
  841. 841 detection: face,
  842. 842 recognition,
  843. 843 expression,
  844. 844 age_gender,
  845. 845 face_quality: quality,
  846. 846 brightness,
  847. 847 sharpness,
  848. 848 occlusion_rate: 0.0,
  849. 849 }
  850. 850}
  851. 851
  852. 852///|
  853. 853/// 生成人脸识别报告
  854. 854pub fn face_recognition_report_to_string(
  855. 855 analysis : FaceAttributeAnalysis,
  856. 856) -> String {
  857. 857● let mut report = "## 人脸识别与表情识别报告\n\n"
  858. 858 report = report + "### 人脸检测\n\n"
  859. 859 report = report + "| 指标 | 值 |\n|------|------|\n"
  860. 860 report = report +
  861. 861 "| 检测置信度 | " +
  862. 862● (analysis.detection.confidence * 100.0).to_string() +
  863. 863 "% |\n"
  864. 864 report = report +
  865. 865 "| 关键点数量 | " +
  866. 866● analysis.detection.num_landmarks.to_string() +
  867. 867 " |\n"
  868. 868 report = report +
  869. 869 "| 是否正面 | " +
  870. 870◐ (if analysis.detection.is_frontal { "是" } else { "否" }) +
  871. 871 " |\n"
  872. 872 report = report +
  873. 873 "| 偏航角 | " +
  874. 874● analysis.detection.yaw.to_string() +
  875. 875 "° |\n"
  876. 876 report = report +
  877. 877 "| 俯仰角 | " +
  878. 878● analysis.detection.pitch.to_string() +
  879. 879 "° |\n"
  880. 880 report = report +
  881. 881 "| 翻滚角 | " +
  882. 882● analysis.detection.roll.to_string() +
  883. 883 "° |\n\n"
  884. 884
  885. 885 report = report + "### 人脸识别\n\n"
  886. 886 report = report + "| 指标 | 值 |\n|------|------|\n"
  887. 887 report = report + "| 身份 | " + analysis.recognition.identity + " |\n"
  888. 888 report = report +
  889. 889 "| 是否已知 | " +
  890. 890● (if analysis.recognition.is_known { "是" } else { "否" }) +
  891. 891 " |\n"
  892. 892 report = report +
  893. 893 "| 相似度 | " +
  894. 894● (analysis.recognition.similarity * 100.0).to_string() +
  895. 895 "% |\n"
  896. 896 report = report +
  897. 897 "| 匹配置信度 | " +
  898. 898● (analysis.recognition.confidence * 100.0).to_string() +
  899. 899 "% |\n\n"
  900. 900
  901. 901 report = report + "### 表情识别\n\n"
  902. 902 report = report + "| 指标 | 值 |\n|------|------|\n"
  903. 903 report = report +
  904. 904 "| 表情 | " +
  905. 905 analysis.expression.dominant_expression +
  906. 906 " |\n"
  907. 907 report = report +
  908. 908 "| 置信度 | " +
  909. 909● (analysis.expression.confidence * 100.0).to_string() +
  910. 910 "% |\n"
  911. 911 report = report +
  912. 912 "| 类别数 | " +
  913. 913● analysis.expression.num_classes.to_string() +
  914. 914 " |\n\n"
  915. 915
  916. 916 report = report + "### 年龄性别估计\n\n"
  917. 917 report = report + "| 指标 | 值 |\n|------|------|\n"
  918. 918 report = report +
  919. 919 "| 估计年龄 | " +
  920. 920● analysis.age_gender.age.to_string() +
  921. 921 " 岁 |\n"
  922. 922 report = report +
  923. 923 "| 年龄范围 | " +
  924. 924● analysis.age_gender.age_range[0].to_string() +
  925. 925 " - " +
  926. 926● analysis.age_gender.age_range[1].to_string() +
  927. 927 " 岁 |\n"
  928. 928 report = report + "| 性别 | " + analysis.age_gender.gender + " |\n"
  929. 929 report = report +
  930. 930 "| 性别置信度 | " +
  931. 931● (analysis.age_gender.gender_confidence * 100.0).to_string() +
  932. 932 "% |\n\n"
  933. 933
  934. 934 report = report + "### 人脸质量\n\n"
  935. 935 report = report + "| 指标 | 值 |\n|------|------|\n"
  936. 936 report = report +
  937. 937 "| 综合质量 | " +
  938. 938● (analysis.face_quality * 100.0).to_string() +
  939. 939 "% |\n"
  940. 940● report = report + "| 亮度 | " + analysis.brightness.to_string() + " |\n"
  941. 941● report = report + "| 锐度 | " + analysis.sharpness.to_string() + " |\n"
  942. 942 report = report +
  943. 943 "| 遮挡率 | " +
  944. 944● (analysis.occlusion_rate * 100.0).to_string() +
  945. 945 "% |\n"
  946. 946
  947. 947 report
  948. 948}