You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

lung_segmentation.py 4.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. # !/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. """
  4. Copyright 2020 Tianshu AI Platform. All Rights Reserved.
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. =============================================================
  15. """
  16. import json
  17. import numpy as np
  18. from skimage.morphology import disk, binary_erosion, binary_closing
  19. from skimage.measure import label, regionprops, find_contours
  20. from skimage.filters import roberts
  21. from scipy import ndimage as ndi
  22. from skimage.segmentation import clear_border
  23. import pydicom as dicom
  24. import os
  25. import logging
  26. def execute(task):
  27. return process(task)
  28. def process(task_dict):
  29. """Lung segmentation based on dcm task method.
  30. Args:
  31. task_dict: imagenet task details.
  32. key: imagenet task key.
  33. """
  34. dcms = task_dict["dcms"]
  35. file_ids = task_dict["medicineFileIds"]
  36. result = []
  37. for i in range(len(task_dict["dcms"])):
  38. temp = {}
  39. temp["id"] = file_ids[i]
  40. image = preprocesss_dcm_image(dcms[i])
  41. # segmentation and wirte coutours to result_path
  42. temp["annotations"] = contour(segmentation(image))
  43. result.append(temp)
  44. logging.info(result)
  45. logging.info("all dcms in one task are processed.")
  46. return {"annotations": json.dumps(result)}
  47. def preprocesss_dcm_image(path):
  48. """Load and preprocesss dcm image.
  49. Args:
  50. path: dcm file path.
  51. """
  52. # result_path = os.path.basename(path).split(".", 1)[0] + ".json"
  53. dcm = dicom.dcmread(path)
  54. image = dcm.pixel_array.astype(np.int16)
  55. # Set outside-of-scan pixels to 0.
  56. image[image == -2000] = 0
  57. # Convert to Hounsfield units (HU)
  58. intercept = dcm.RescaleIntercept
  59. slope = dcm.RescaleSlope
  60. if slope != 1:
  61. image = slope * image.astype(np.float64)
  62. image = image.astype(np.int16)
  63. image += np.int16(intercept)
  64. logging.info("preprocesss_dcm_image done.")
  65. return np.array(image, dtype=np.int16)
  66. def segmentation(image):
  67. """Segments the lung from the given 2D slice.
  68. Args:
  69. image: single image in one dcm.
  70. """
  71. # Step 1: Convert into a binary image.
  72. binary = image < -350
  73. # Step 2: Remove the blobs connected to the border of the image.
  74. cleared = clear_border(binary)
  75. # Step 3: Label the image.
  76. label_image = label(cleared)
  77. # Step 4: Keep the labels with 2 largest areas.
  78. areas = [r.area for r in regionprops(label_image)]
  79. areas.sort()
  80. if len(areas) > 2:
  81. for region in regionprops(label_image):
  82. if region.area < areas[-2]:
  83. for coordinates in region.coords:
  84. label_image[coordinates[0], coordinates[1]] = 0
  85. binary = label_image > 0
  86. # Step 5: Erosion operation with a disk of radius 2. This operation is seperate the lung nodules attached to the blood vessels.
  87. selem = disk(1)
  88. binary = binary_erosion(binary, selem)
  89. # Step 6: Closure operation with a disk of radius 10. This operation is to keep nodules attached to the lung wall.
  90. selem = disk(16)
  91. binary = binary_closing(binary, selem)
  92. # Step 7: Fill in the small holes inside the binary mask of lungs.
  93. for _ in range(3):
  94. edges = roberts(binary)
  95. binary = ndi.binary_fill_holes(edges)
  96. logging.info("lung segmentation done.")
  97. return binary
  98. def contour(image):
  99. """Get contours of segmentation.
  100. Args:
  101. seg: segmentation of lung.
  102. """
  103. result = []
  104. contours = find_contours(image, 0.5)
  105. if len(contours) > 2:
  106. contours.sort(key=lambda x: int(x.shape[0]))
  107. contours = contours[-2:]
  108. for n, contour in enumerate(contours):
  109. # result.append({"type":n, "annotation":contour.tolist()})
  110. result.append({"type": n, "annotation": np.flip(contour, 1).tolist()})
  111. return result

一站式算法开发平台、高性能分布式深度学习框架、先进算法模型库、视觉模型炼知平台、数据可视化分析平台等一系列平台及工具,在模型高效分布式训练、数据处理和可视分析、模型炼知和轻量化等技术上形成独特优势,目前已在产学研等各领域近千家单位及个人提供AI应用赋能