0

I learn how to convert DCM file to Raw file .Got the code from Git Hub:
https://github.com/xiasun/dicom2raw/blob/master/dicom2raw.py
And it got a error"Can't convert 'bytes' object to str implicitly" on the line
"allInOne += dataset.PixelData"
I try to use "encode("utf-8")",but it make allInOne to be empty. By the way ,Is there any code to generate the .mhd file corresponding to the .raw file?

import dicom  
import os  
import numpy  
import sys  
dicomPath = "C:/DataLuna16pen/dcmdata/"
lstFilesDCM = []  # create an empty list
for dirName, subdirList, fileList in os.walk(dicomPath):  
    allInOne = ""
    print(subdirList)
    i=0
    for filename in fileList:
        i+=1
        if "".join(filename).endswith((".dcm", ".DCM")): 
            path = dicomPath + "".join(filename)
            dataset = dicom.read_file(path)
            for n,val in enumerate(dataset.pixel_array.flat): 
                dataset.pixel_array.flat[n] = val / 60
                if val < 0:
                    dataset.pixel_array.flat[n] = 0

            dataset.PixelData = numpy.uint8(dataset.pixel_array).tostring() 
            allInOne += dataset.PixelData        
            print ("slice " + "".join(filename) + " done ",end=" ")
            print (i)

    newFile = open("./all_in_one.raw", "wb")
    newFile.write(allInOne)
    newFile.close()
    print ("RAW file generated")
PHE
  • 63
  • 8
  • Why are you trying to write the pixel data into a string? – E_net4 Jan 02 '18 at 11:08
  • I try run the code from reference link. He had comment ## convert int16 to int8.## I do not fully understand the code . my purpose is to convert one patient`s Dicom slices to raw file and mhd file. Thanks you ~ – PHE Jan 02 '18 at 13:36

1 Answers1

1

There are several things:

  • PyDicom still doesn't read compressed DICOMs properly (loseless jpeg). You should check Transfer Syntax of the files to check if this is the case. As a workaround you can use GDCM tool dcmdjpeg
  • you should not convert byte array into string (np.array.tostring returns in fact the array of bytes)
  • for writing mha files, take a look at MedPy. You can also use ITK directly. There is python wrapper and SimpleITK - some kind lightweight modification of ITK
Bartłomiej
  • 1,068
  • 1
  • 14
  • 23