#Peichenhao-2019.9.9 NII2DCM
#help from ITK-Dicom Series From Array(https://simpleitk.readthedocs.io/en/next/Examples/DicomSeriesFromArray/Documentation.html)
#you need to change datapath and outputpath to your own
#such as my outputpath='H:/1data/mytest/';datapath = 'F:/1PHD/3Data/9-med/Doctor/aanii.gz/cql.nii.gz'

from __future__ import print_function
import SimpleITK as sitk
import sys, time, os
import numpy as np

outputpath='H:/1data/mytest/'

def writeSlices(series_tag_values, new_img, i):
    print(i)
    image_slice = new_img[:, :, i]

    # Tags shared by the series.
    list(map(lambda tag_value: image_slice.SetMetaData(tag_value[0], tag_value[1]), series_tag_values))

    # Slice specific tags.
    image_slice.SetMetaData("0008|0012", time.strftime("%Y%m%d"))  # Instance Creation Date
    image_slice.SetMetaData("0008|0013", time.strftime("%H%M%S"))  # Instance Creation Time

    # Setting the type to CT preserves the slice location.
    image_slice.SetMetaData("0008|0060", "CT")  # set the type to CT so the thickness is carried over

    # (0020, 0032) image position patient determines the 3D spacing between slices.
    image_slice.SetMetaData("0020|0032", '\\'.join(
        map(str, new_img.TransformIndexToPhysicalPoint((0, 0, i)))))  # Image Position (Patient)
    image_slice.SetMetaData("0020,0013", str(i))  # Instance Number

    # Write to the output directory and add the extension dcm, to force writing in DICOM format.
    writer.SetFileName(os.path.join(outputpath, str(i) + '.dcm'))
    writer.Execute(image_slice)


# Create a new series from a nii.gz
datapath = 'F:/1PHD/3Data/9-med/Doctor/aanii.gz/cql.nii.gz'
itk_img = sitk.ReadImage(datapath)
orig_size = np.array (itk_img.GetSize(),dtype=np.int)
orig_spacing = list(itk_img. GetSpacing())
new_img = sitk.GetArrayFromImage(itk_img)
print(new_img.shape)
print(orig_spacing)
new_img = sitk.GetImageFromArray(new_img)
new_img.SetSpacing(orig_spacing)

# Write the 3D image as a series
# IMPORTANT: There are many DICOM tags that need to be updated when you modify an
#            original image. This is a delicate opration and requires knowlege of
#            the DICOM standard. This example only modifies some. For a more complete
#            list of tags that need to be modified see:
#                           http://gdcm.sourceforge.net/wiki/index.php/Writing_DICOM
#            If it is critical for your work to generate valid DICOM files,
#            It is recommended to use David Clunie's Dicom3tools to validate the files
#                           (http://www.dclunie.com/dicom3tools.html).

writer = sitk.ImageFileWriter()
# Use the study/series/frame of reference information given in the meta-data
# dictionary and not the automatically generated information from the file IO
writer.KeepOriginalImageUIDOn()

modification_time = time.strftime("%H%M%S")
modification_date = time.strftime("%Y%m%d")

# Copy some of the tags and add the relevant tags indicating the change.
# For the series instance UID (0020|000e), each of the components is a number, cannot start
# with zero, and separated by a '.' We create a unique series ID using the date and time.
# tags of interest:
direction = new_img.GetDirection()
series_tag_values = [("0008|0031", modification_time),  # Series Time
                     ("0008|0021", modification_date),  # Series Date
                     ("0008|0008", "DERIVED\\SECONDARY"),  # Image Type
                     ("0020|000e", "1.2.826.0.1.3680043.2.1125." + modification_date + ".1" + modification_time),
                     # Series Instance UID
                     ("0020|0037",
                      '\\'.join(map(str, (direction[0], direction[3], direction[6],  # Image Orientation (Patient)
                                          direction[1], direction[4], direction[7])))),
                     ("0008|103e", "Created-SimpleITK")]  # Series Description

# Write slices to output directory
print(new_img.GetDepth())
list(map(lambda i: writeSlices(series_tag_values, new_img, i), range(new_img.GetDepth())))
print('Finish!')