20 """ A SimpleITK example that demonstrates how to read a raw image. """
26 import SimpleITK
as sitk
38 Read a raw binary scalar image.
42 binary_file_name (str): Raw, binary image file content.
43 image_size (tuple like): Size of image (e.g. [2048,2048])
44 sitk_pixel_type (SimpleITK pixel type: Pixel type of data (e.g.
46 image_spacing (tuple like): Optional image spacing, if none given assumed
48 image_origin (tuple like): Optional image origin, if none given assumed to
50 big_endian (bool): Optional byte order indicator, if True big endian, else
55 SimpleITK image or None if fails.
59 sitk.sitkUInt8:
"MET_UCHAR",
60 sitk.sitkInt8:
"MET_CHAR",
61 sitk.sitkUInt16:
"MET_USHORT",
62 sitk.sitkInt16:
"MET_SHORT",
63 sitk.sitkUInt32:
"MET_UINT",
64 sitk.sitkInt32:
"MET_INT",
65 sitk.sitkUInt64:
"MET_ULONG_LONG",
66 sitk.sitkInt64:
"MET_LONG_LONG",
67 sitk.sitkFloat32:
"MET_FLOAT",
68 sitk.sitkFloat64:
"MET_DOUBLE",
73 "1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1",
77 "ObjectType = Image\n".encode(),
78 (f
"NDims = {dim}\n").encode(),
79 (
"DimSize = " +
" ".join([str(v)
for v
in image_size]) +
"\n").encode(),
83 " ".join([str(v)
for v
in image_spacing])
85 else " ".join([
"1"] * dim)
92 " ".join([str(v)
for v
in image_origin])
94 else " ".join([
"0"] * dim) +
"\n"
97 (
"TransformMatrix = " + direction_cosine[dim - 2] +
"\n").encode(),
98 (
"ElementType = " + pixel_dict[sitk_pixel_type] +
"\n").encode(),
99 "BinaryData = True\n".encode(),
100 (
"BinaryDataByteOrderMSB = " + str(big_endian) +
"\n").encode(),
102 (
"ElementDataFile = " + os.path.abspath(binary_file_name) +
"\n").encode(),
104 fp = tempfile.NamedTemporaryFile(suffix=
".mhd", delete=
False)
110 fp.writelines(header)
117 parser = argparse.ArgumentParser()
118 parser.add_argument(
"raw_file_name", help=
"path to raw binary image file")
120 "out_file_name", help=
"output file name when image read as little endian"
124 type=
lambda v: v.lower()
in {
"1",
"true"},
125 help=
"'false' for little ending or 'true'for big " "endian",
128 "sitk_pixel_type", help=
"SimpleITK pixel type (e.g. sitk.sitkUInt16)"
130 parser.add_argument(
"sz", nargs=
"+", help=
"image size, x,y,...", type=int)
131 args = parser.parse_args()
133 string_to_pixelType = {
134 "sitkUInt8": sitk.sitkUInt8,
135 "sitkInt8": sitk.sitkInt8,
136 "sitkUInt16": sitk.sitkUInt16,
137 "sitkInt16": sitk.sitkInt16,
138 "sitkUInt32": sitk.sitkUInt32,
139 "sitkInt32": sitk.sitkInt32,
140 "sitkUInt64": sitk.sitkUInt64,
141 "sitkInt64": sitk.sitkInt64,
142 "sitkFloat32": sitk.sitkFloat32,
143 "sitkFloat64": sitk.sitkFloat64,
148 binary_file_name=args.raw_file_name,
150 sitk_pixel_type=string_to_pixelType[args.sitk_pixel_type],
151 big_endian=args.big_endian,
156 if "SITK_NOSHOW" not in os.environ: