image.domain\medical\medical_enhancement.mbt

88.2% · 134 / 152 points · 604 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/// # 医学增强 medical/medical_enhancement
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 医学图像增强(v19.0.0)
  7. 7// 医学图像分割、配准、增强、DICOM 处理、病灶检测
  8. 8
  9. 9///|
  10. 10/// 医学图像类型
  11. 11/// `#non_exhaustive` 表示未来可能添加新构造器
  12. 12#derive(Eq)
  13. 13#non_exhaustive
  14. 14pub(all) enum MedicalImageType {
  15. 15 CT
  16. 16 MRI
  17. 17 XRay
  18. 18 Ultrasound
  19. 19 PET
  20. 20 SPECT
  21. 21 Mammography
  22. 22 Fluoroscopy
  23. 23 Unknown
  24. 24}
  25. 25
  26. 26///|
  27. 27pub extend MedicalImageType with Eq::{not_equal, equal}
  28. 28
  29. 29///|
  30. 30/// 医学图像
  31. 31pub(all) struct MedicalImage {
  32. 32 width : Int32
  33. 33 height : Int32
  34. 34 slices : Int32
  35. 35 data : Array[Double]
  36. 36 image_type : MedicalImageType
  37. 37 pixel_spacing_x : Double
  38. 38 pixel_spacing_y : Double
  39. 39 slice_thickness : Double
  40. 40 window_center : Double
  41. 41 window_width : Double
  42. 42}
  43. 43
  44. 44///|
  45. 45/// 感兴趣区域(ROI)
  46. 46pub(all) struct RegionOfInterest {
  47. 47 id : Int32
  48. 48 name : String
  49. 49 x : Int32
  50. 50 y : Int32
  51. 51 width : Int32
  52. 52 height : Int32
  53. 53 slice : Int32
  54. 54 volume : Double
  55. 55 mean_intensity : Double
  56. 56 std_intensity : Double
  57. 57 confidence : Double
  58. 58}
  59. 59
  60. 60///|
  61. 61/// 病灶
  62. 62pub(all) struct Lesion {
  63. 63 id : Int32
  64. 64 lesion_type : String
  65. 65 x : Double
  66. 66 y : Double
  67. 67 z : Double
  68. 68 diameter : Double
  69. 69 volume : Double
  70. 70 intensity : Double
  71. 71 margin : String // "well_defined" / "ill_defined" / "spiculated"
  72. 72 shape : String // "round" / "oval" / "irregular"
  73. 73 density : String // "solid" / "cystic" / "mixed" / "calcified"
  74. 74 confidence : Double
  75. 75 birads_category : Int32 // BI-RADS 1-6
  76. 76}
  77. 77
  78. 78///|
  79. 79/// 医学图像配准结果
  80. 80pub(all) struct MedicalRegistrationResult {
  81. 81 transformation : Array[Double] // 4x4 变换矩阵
  82. 82 similarity : Double
  83. 83 iterations : Int32
  84. 84 converged : Bool
  85. 85 registration_type : String // "rigid" / "affine" / "deformable"
  86. 86}
  87. 87
  88. 88///|
  89. 89/// 医学图像分割配置
  90. 90pub(all) struct MedicalSegmentationConfig {
  91. 91 method_type : String // "threshold" / "region_growing" / "level_set" / "watershed"
  92. 92 lower_threshold : Double
  93. 93 upper_threshold : Double
  94. 94 seed_points : Array[(Int32, Int32, Int32)]
  95. 95 smoothness : Double
  96. 96 curvature_weight : Double
  97. 97}
  98. 98
  99. 99///|
  100. 100/// 窗宽窗位配置
  101. 101pub(all) struct WindowLevelConfig {
  102. 102 center : Double
  103. 103 width : Double
  104. 104 preset : String // "brain" / "lung" / "abdomen" / "bone" / "soft_tissue" / "custom"
  105. 105}
  106. 106
  107. 107///|
  108. 108/// 医学图像质量指标
  109. 109pub(all) struct MedicalImageQuality {
  110. 110 snr : Double // 信噪比
  111. 111 cnr : Double // 对比噪声比
  112. 112 sharpness : Double
  113. 113 noise_level : Double
  114. 114 artifact_score : Double
  115. 115 overall_quality : Double // 1-5 分
  116. 116}
  117. 117
  118. 118///|
  119. 119/// 创建默认医学分割配置
  120. 120pub fn create_default_medical_segmentation_config() -> MedicalSegmentationConfig {
  121. 121● MedicalSegmentationConfig::{
  122. 122 method_type: "threshold",
  123. 123 lower_threshold: 0.0,
  124. 124 upper_threshold: 255.0,
  125. 125 seed_points: [],
  126. 126 smoothness: 1.0,
  127. 127 curvature_weight: 1.0,
  128. 128 }
  129. 129}
  130. 130
  131. 131///|
  132. 132/// 创建默认窗宽窗位配置
  133. 133pub fn create_default_window_level(preset : String) -> WindowLevelConfig {
  134. 134● if preset == "brain" {
  135. 135● WindowLevelConfig::{ center: 40.0, width: 80.0, preset, }
  136. 136● } else if preset == "lung" {
  137. 137● WindowLevelConfig::{ center: -600.0, width: 1500.0, preset, }
  138. 138● } else if preset == "abdomen" {
  139. 139● WindowLevelConfig::{ center: 40.0, width: 400.0, preset, }
  140. 140● } else if preset == "bone" {
  141. 141● WindowLevelConfig::{ center: 300.0, width: 1500.0, preset, }
  142. 142● } else if preset == "soft_tissue" {
  143. 143● WindowLevelConfig::{ center: 50.0, width: 350.0, preset, }
  144. 144 } else {
  145. 145● WindowLevelConfig::{ center: 128.0, width: 256.0, preset: "custom", }
  146. 146 }
  147. 147}
  148. 148
  149. 149///|
  150. 150/// 应用窗宽窗位
  151. 151pub fn apply_window_level_medical(
  152. 152 image : MedicalImage,
  153. 153 config : WindowLevelConfig,
  154. 154) -> @types.Image {
  155. 155● let w = image.width
  156. 156 let h = image.height
  157. 157 let out : Array[Byte] = []
  158. 158 let lower = config.center - config.width / 2.0
  159. 159 let upper = config.center + config.width / 2.0
  160. 160
  161. 161 for i in 0..<(w * h) {
  162. 162● let pixel = image.data[i]
  163. 163 let normalized = if upper > lower {
  164. 164● (pixel - lower) / (upper - lower)
  165. 165 } else {
  166. 166● 0.5
  167. 167 }
  168. 168 let clamped = if normalized < 0.0 {
  169. 169○ 0.0
  170. 170● } else if normalized > 1.0 {
  171. 171● 1.0
  172. 172 } else {
  173. 173● normalized
  174. 174 }
  175. 175● let value = (clamped * 255.0).to_int()
  176. 176● out.push(if value > 127 { b'\xFF' } else { b'\x00' })
  177. 177 }
  178. 178
  179. 179 @types.Image::{
  180. 180 width: w,
  181. 181 height: h,
  182. 182 channels: 1,
  183. 183● data: Bytes::from_array(out),
  184. 184 }
  185. 185}
  186. 186
  187. 187///|
  188. 188/// 医学图像阈值分割
  189. 189pub fn medical_threshold_segmentation(
  190. 190 image : MedicalImage,
  191. 191 lower : Double,
  192. 192 upper : Double,
  193. 193) -> Array[Bool] {
  194. 194● let total = image.width * image.height * image.slices
  195. 195 let mask : Array[Bool] = []
  196. 196
  197. 197 for i in 0..<total {
  198. 198● let pixel = image.data[i]
  199. 199● mask.push(pixel >= lower && pixel <= upper)
  200. 200 }
  201. 201
  202. 202 mask
  203. 203}
  204. 204
  205. 205///|
  206. 206/// 区域生长分割
  207. 207pub fn region_growing_segmentation(
  208. 208 image : MedicalImage,
  209. 209 seed_x : Int32,
  210. 210 seed_y : Int32,
  211. 211 seed_z : Int32,
  212. 212 threshold : Double,
  213. 213) -> Array[Bool] {
  214. 214● let w = image.width
  215. 215 let h = image.height
  216. 216 let s = image.slices
  217. 217 let total = w * h * s
  218. 218 let mask : Array[Bool] = []
  219. 219 for _ in 0..<total {
  220. 220● mask.push(false)
  221. 221 }
  222. 222
  223. 223 let seed_idx = seed_z * w * h + seed_y * w + seed_x
  224. 224 if seed_idx < 0 || seed_idx >= total {
  225. 225● return mask
  226. 226 }
  227. 227
  228. 228 let seed_value = image.data[seed_idx]
  229. 229 let queue_x : Array[Int32] = [seed_x]
  230. 230 let queue_y : Array[Int32] = [seed_y]
  231. 231 let queue_z : Array[Int32] = [seed_z]
  232. 232 mask[seed_idx] = true
  233. 233 let mut queue_idx = 0
  234. 234
  235. 235● while queue_idx < queue_x.length() {
  236. 236● let cx = queue_x[queue_idx]
  237. 237 let cy = queue_y[queue_idx]
  238. 238 let cz = queue_z[queue_idx]
  239. 239 queue_idx += 1
  240. 240
  241. 241 // 6 邻域
  242. 242 let neighbors = [
  243. 243 (cx + 1, cy, cz),
  244. 244 (cx - 1, cy, cz),
  245. 245 (cx, cy + 1, cz),
  246. 246 (cx, cy - 1, cz),
  247. 247 (cx, cy, cz + 1),
  248. 248 (cx, cy, cz - 1),
  249. 249 ]
  250. 250
  251. 251 for _tup0 in neighbors {
  252. 252● let (nx, ny, nz) = _tup0
  253. 253 if nx < 0 || nx >= w || ny < 0 || ny >= h || nz < 0 || nz >= s {
  254. 254● continue
  255. 255 }
  256. 256 let nidx = nz * w * h + ny * w + nx
  257. 257 if mask[nidx] {
  258. 258● continue
  259. 259 }
  260. 260 let nvalue = image.data[nidx]
  261. 261● if (nvalue - seed_value).abs() < threshold {
  262. 262● mask[nidx] = true
  263. 263● queue_x.push(nx)
  264. 264● queue_y.push(ny)
  265. 265● queue_z.push(nz)
  266. 266 }
  267. 267 }
  268. 268 }
  269. 269
  270. 270 mask
  271. 271}
  272. 272
  273. 273///|
  274. 274/// 计算 ROI 统计信息
  275. 275pub fn calculate_roi_stats(
  276. 276 image : MedicalImage,
  277. 277 mask : Array[Bool],
  278. 278) -> (Double, Double, Int32) {
  279. 279● let mut sum = 0.0
  280. 280 let mut sum_sq = 0.0
  281. 281 let mut count = 0
  282. 282
  283. 283● for i in 0..<mask.length() {
  284. 284● if mask[i] && i < image.data.length() {
  285. 285● let pixel = image.data[i]
  286. 286 sum += pixel
  287. 287 sum_sq += pixel * pixel
  288. 288 count += 1
  289. 289 }
  290. 290 }
  291. 291
  292. 292● let mean = if count > 0 { sum / count.to_double() } else { 0.0 }
  293. 293 let variance = if count > 0 {
  294. 294● sum_sq / count.to_double() - mean * mean
  295. 295 } else {
  296. 296● 0.0
  297. 297 }
  298. 298● let std = if variance > 0.0 { variance.sqrt() } else { 0.0 }
  299. 299
  300. 300 (mean, std, count)
  301. 301}
  302. 302
  303. 303///|
  304. 304/// 简单病灶检测(基于强度和形状)
  305. 305pub fn detect_lesions_simple(
  306. 306 image : MedicalImage,
  307. 307 min_diameter : Double,
  308. 308 max_diameter : Double,
  309. 309) -> Array[Lesion] {
  310. 310● let lesions : Array[Lesion] = []
  311. 311 let w = image.width
  312. 312 let h = image.height
  313. 313
  314. 314 // 简化版:基于局部最大值的病灶检测
  315. 315 let mut lesion_id = 0
  316. 316 for y in 5..<(h - 5) {
  317. 317● for x in 5..<(w - 5) {
  318. 318● let idx = y * w + x
  319. 319 let pixel = image.data[idx]
  320. 320 if pixel < 100.0 {
  321. 321● continue
  322. 322 }
  323. 323
  324. 324 // 检查是否为局部最大值
  325. 325 let mut is_local_max = true
  326. 326 for dy in -3..<4 {
  327. 327● for dx in -3..<4 {
  328. 328● if dx == 0 && dy == 0 {
  329. 329● continue
  330. 330 }
  331. 331 let neighbor = image.data[(y + dy) * w + (x + dx)]
  332. 332 if neighbor > pixel {
  333. 333● is_local_max = false
  334. 334 }
  335. 335 }
  336. 336 }
  337. 337
  338. 338 if is_local_max {
  339. 339 // 估算直径
  340. 340● let mut diameter = 0.0
  341. 341 for r in 1..<10 {
  342. 342● let mut all_above = true
  343. 343 for dy in -r..<(r + 1) {
  344. 344● for dx in -r..<(r + 1) {
  345. 345● let nx = x + dx
  346. 346 let ny = y + dy
  347. 347 if nx >= 0 && nx < w && ny >= 0 && ny < h {
  348. 348● if image.data[ny * w + nx] < pixel * 0.5 {
  349. 349● all_above = false
  350. 350 }
  351. 351 }
  352. 352 }
  353. 353 }
  354. 354 if all_above {
  355. 355● diameter = r.to_double() * 2.0
  356. 356 }
  357. 357 }
  358. 358
  359. 359 if diameter >= min_diameter && diameter <= max_diameter {
  360. 360● lesions.push(Lesion::{
  361. 361 id: lesion_id,
  362. 362 lesion_type: "nodule",
  363. 363● x: x.to_double(),
  364. 364● y: y.to_double(),
  365. 365 z: 0.0,
  366. 366 diameter,
  367. 367 volume: diameter * diameter * diameter * 3.14159 / 6.0,
  368. 368 intensity: pixel,
  369. 369 margin: "well_defined",
  370. 370 shape: "round",
  371. 371 density: "solid",
  372. 372 confidence: 0.7,
  373. 373 birads_category: 3,
  374. 374 })
  375. 375 lesion_id += 1
  376. 376 }
  377. 377 }
  378. 378 }
  379. 379 }
  380. 380
  381. 381 lesions
  382. 382}
  383. 383
  384. 384///|
  385. 385/// 医学图像配准(简化版互信息)
  386. 386pub fn medical_image_registration(
  387. 387 fixed : MedicalImage,
  388. 388 moving : MedicalImage,
  389. 389 max_iterations : Int32,
  390. 390) -> MedicalRegistrationResult {
  391. 391● let transformation : Array[Double] = [
  392. 392 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
  393. 393 ]
  394. 394
  395. 395 let mut similarity = 0.0
  396. 396 let mut converged = false
  397. 397 let mut iterations = 0
  398. 398
  399. 399 for iter in 0..<max_iterations {
  400. 400● iterations = iter + 1
  401. 401 // 简化版:计算归一化互相关
  402. 402 let mut sum_fixed = 0.0
  403. 403 let mut sum_moving = 0.0
  404. 404 let mut sum_product = 0.0
  405. 405 let mut sum_fixed_sq = 0.0
  406. 406 let mut sum_moving_sq = 0.0
  407. 407● let count = if fixed.data.length() < moving.data.length() {
  408. 408○ fixed.data.length()
  409. 409 } else {
  410. 410● moving.data.length()
  411. 411 }
  412. 412
  413. 413 for i in 0..<count {
  414. 414● let f = fixed.data[i]
  415. 415 let m = moving.data[i]
  416. 416 sum_fixed += f
  417. 417 sum_moving += m
  418. 418 sum_product += f * m
  419. 419 sum_fixed_sq += f * f
  420. 420 sum_moving_sq += m * m
  421. 421 }
  422. 422
  423. 423● let mean_f = sum_fixed / count.to_double()
  424. 424● let mean_m = sum_moving / count.to_double()
  425. 425● let cov = sum_product / count.to_double() - mean_f * mean_m
  426. 426● let var_f = sum_fixed_sq / count.to_double() - mean_f * mean_f
  427. 427● let var_m = sum_moving_sq / count.to_double() - mean_m * mean_m
  428. 428 let ncc = if var_f > 0.0 && var_m > 0.0 {
  429. 429● cov / (var_f * var_m).sqrt()
  430. 430 } else {
  431. 431● 0.0
  432. 432 }
  433. 433
  434. 434● if (ncc - similarity).abs() < 0.001 {
  435. 435● converged = true
  436. 436 similarity = ncc
  437. 437 break
  438. 438 }
  439. 439 similarity = ncc
  440. 440 }
  441. 441
  442. 442 MedicalRegistrationResult::{
  443. 443 transformation,
  444. 444 similarity,
  445. 445 iterations,
  446. 446 converged,
  447. 447 registration_type: "rigid",
  448. 448 }
  449. 449}
  450. 450
  451. 451///|
  452. 452/// 计算医学图像质量指标
  453. 453pub fn calculate_medical_image_quality(
  454. 454 image : MedicalImage,
  455. 455) -> MedicalImageQuality {
  456. 456● let w = image.width
  457. 457 let h = image.height
  458. 458 let total = w * h
  459. 459
  460. 460 // 计算 SNR
  461. 461 let mut sum = 0.0
  462. 462 let mut sum_sq = 0.0
  463. 463 for i in 0..<total {
  464. 464● let pixel = image.data[i]
  465. 465 sum += pixel
  466. 466 sum_sq += pixel * pixel
  467. 467 }
  468. 468● let mean = sum / total.to_double()
  469. 469● let variance = sum_sq / total.to_double() - mean * mean
  470. 470● let std = if variance > 0.0 { variance.sqrt() } else { 1.0 }
  471. 471◐ let snr = if std > 0.0 { mean / std } else { 0.0 }
  472. 472
  473. 473 // 计算清晰度(基于梯度)
  474. 474 let mut sharpness = 0.0
  475. 475 for y in 1..<(h - 1) {
  476. 476● for x in 1..<(w - 1) {
  477. 477● let idx = y * w + x
  478. 478 let gx = image.data[idx + 1] - image.data[idx - 1]
  479. 479 let gy = image.data[idx + w] - image.data[idx - w]
  480. 480● sharpness += (gx * gx + gy * gy).sqrt()
  481. 481 }
  482. 482 }
  483. 483● sharpness /= total.to_double()
  484. 484
  485. 485 let noise_level = std
  486. 486 let cnr = snr * 0.8
  487. 487 let artifact_score = 1.0
  488. 488 let overall_quality = if snr > 10.0 && sharpness > 5.0 {
  489. 489○ 5.0
  490. 490● } else if snr > 5.0 {
  491. 491● 3.0
  492. 492 } else {
  493. 493● 2.0
  494. 494 }
  495. 495
  496. 496 MedicalImageQuality::{
  497. 497 snr,
  498. 498 cnr,
  499. 499 sharpness,
  500. 500 noise_level,
  501. 501 artifact_score,
  502. 502 overall_quality,
  503. 503 }
  504. 504}
  505. 505
  506. 506///|
  507. 507/// 生成医学图像报告
  508. 508pub fn medical_image_report_to_string(
  509. 509 image : MedicalImage,
  510. 510 lesions : Array[Lesion],
  511. 511 quality : MedicalImageQuality,
  512. 512) -> String {
  513. 513● let mut report = "## 医学图像分析报告\n\n"
  514. 514 report = report + "### 图像信息\n\n"
  515. 515 report = report + "| 指标 | 值 |\n|------|------|\n"
  516. 516 let type_str = if image.image_type == MedicalImageType::CT {
  517. 517● "CT"
  518. 518● } else if image.image_type == MedicalImageType::MRI {
  519. 519● "MRI"
  520. 520○ } else if image.image_type == MedicalImageType::XRay {
  521. 521○ "X-Ray"
  522. 522○ } else if image.image_type == MedicalImageType::Ultrasound {
  523. 523○ "超声"
  524. 524○ } else if image.image_type == MedicalImageType::PET {
  525. 525○ "PET"
  526. 526○ } else if image.image_type == MedicalImageType::SPECT {
  527. 527○ "SPECT"
  528. 528○ } else if image.image_type == MedicalImageType::Mammography {
  529. 529○ "乳腺钼靶"
  530. 530○ } else if image.image_type == MedicalImageType::Fluoroscopy {
  531. 531○ "透视"
  532. 532 } else {
  533. 533○ "未知"
  534. 534 }
  535. 535 report = report + "| 类型 | " + type_str + " |\n"
  536. 536 report = report +
  537. 537 "| 尺寸 | " +
  538. 538● image.width.to_string() +
  539. 539 "x" +
  540. 540● image.height.to_string() +
  541. 541 "x" +
  542. 542● image.slices.to_string() +
  543. 543 " |\n"
  544. 544 report = report +
  545. 545 "| 窗宽窗位 | " +
  546. 546● image.window_center.to_string() +
  547. 547 "/" +
  548. 548● image.window_width.to_string() +
  549. 549 " |\n\n"
  550. 550
  551. 551 report = report + "### 图像质量\n\n"
  552. 552 report = report + "| 指标 | 值 |\n|------|------|\n"
  553. 553● report = report + "| SNR | " + quality.snr.to_string() + " dB |\n"
  554. 554● report = report + "| CNR | " + quality.cnr.to_string() + " |\n"
  555. 555● report = report + "| 清晰度 | " + quality.sharpness.to_string() + " |\n"
  556. 556 report = report +
  557. 557 "| 噪声水平 | " +
  558. 558● quality.noise_level.to_string() +
  559. 559 " |\n"
  560. 560 report = report +
  561. 561 "| 综合质量 | " +
  562. 562● quality.overall_quality.to_string() +
  563. 563 "/5.0 |\n\n"
  564. 564
  565. 565● if lesions.length() > 0 {
  566. 566● report = report + "### 检测到的病灶\n\n"
  567. 567 report = report +
  568. 568 "| ID | 类型 | 位置(X,Y,Z) | 直径 | 体积 | 强度 | 形状 | 密度 | 置信度 | BI-RADS |\n"
  569. 569 report = report +
  570. 570 "|----|------|-------------|------|------|------|------|------|--------|---------|\n"
  571. 571 for lesion in lesions {
  572. 572● report = report +
  573. 573 "| " +
  574. 574● lesion.id.to_string() +
  575. 575 " | " +
  576. 576 lesion.lesion_type +
  577. 577 " | " +
  578. 578● lesion.x.to_string() +
  579. 579 "," +
  580. 580● lesion.y.to_string() +
  581. 581 "," +
  582. 582● lesion.z.to_string() +
  583. 583 " | " +
  584. 584● lesion.diameter.to_string() +
  585. 585 " | " +
  586. 586● lesion.volume.to_string() +
  587. 587 " | " +
  588. 588● lesion.intensity.to_string() +
  589. 589 " | " +
  590. 590 lesion.shape +
  591. 591 " | " +
  592. 592 lesion.density +
  593. 593 " | " +
  594. 594● (lesion.confidence * 100.0).to_string() +
  595. 595 "% | " +
  596. 596● lesion.birads_category.to_string() +
  597. 597 " |\n"
  598. 598 }
  599. 599 } else {
  600. 600● report = report + "### 病灶检测\n\n未检测到明显病灶。\n"
  601. 601 }
  602. 602
  603. 603 report
  604. 604}