Convert a single DICOM image to a common image type.
(input_file_name, output_file_name, new_width=None)
| 31 | |
| 32 | |
| 33 | def convert_image(input_file_name, output_file_name, new_width=None): |
| 34 | """ Convert a single DICOM image to a common image type. """ |
| 35 | try: |
| 36 | image_file_reader = sitk.ImageFileReader() |
| 37 | # only read DICOM images |
| 38 | image_file_reader.SetImageIO("GDCMImageIO") |
| 39 | image_file_reader.SetFileName(input_file_name) |
| 40 | image_file_reader.ReadImageInformation() |
| 41 | image_size = list(image_file_reader.GetSize()) |
| 42 | if len(image_size) == 3 and image_size[2] == 1: |
| 43 | image_size[2] = 0 |
| 44 | image_file_reader.SetExtractSize(image_size) |
| 45 | image = image_file_reader.Execute() |
| 46 | if new_width: |
| 47 | original_size = image.GetSize() |
| 48 | original_spacing = image.GetSpacing() |
| 49 | new_spacing = [ |
| 50 | (original_size[0] - 1) * original_spacing[0] / (new_width - 1) |
| 51 | ] * 2 |
| 52 | new_size = [ |
| 53 | new_width, |
| 54 | int((original_size[1] - 1) * original_spacing[1] / new_spacing[1]), |
| 55 | ] |
| 56 | image = sitk.Resample( |
| 57 | image1=image, |
| 58 | size=new_size, |
| 59 | transform=sitk.Transform(), |
| 60 | interpolator=sitk.sitkLinear, |
| 61 | outputOrigin=image.GetOrigin(), |
| 62 | outputSpacing=new_spacing, |
| 63 | outputDirection=image.GetDirection(), |
| 64 | defaultPixelValue=0, |
| 65 | outputPixelType=image.GetPixelID(), |
| 66 | ) |
| 67 | # If a single channel image, rescale to [0,255] and cast to UInt8. |
| 68 | if image.GetNumberOfComponentsPerPixel() == 1: |
| 69 | image = sitk.RescaleIntensity(image, 0, 255) |
| 70 | image = sitk.Cast(image, sitk.sitkUInt8) |
| 71 | sitk.WriteImage(image, output_file_name) |
| 72 | return True |
| 73 | except RuntimeError: |
| 74 | return False |
| 75 | |
| 76 | |
| 77 | def convert_images(input_file_names, output_file_names, new_width): |
nothing calls this directly
no test coverage detected