Search code examples
c++opencvdcmtk

Read a 3D Dicom image with DCMTK and convert it to OpenCV Mat


I have a dicom 3D image which is [512,512,5] (rows, cols, slices). I want to read it with DCMTK toolkit and convert it to a OpenCV Mat object. The image is 16 bits unsigned int.

My question is: Does anyone know the correct way to convert this dicom image into a Mat object? How to properly read all the slices with the method getOutputData?


Solution

  • Based on the comments of @Alan Birtles, there is the possibility to specify the frame you want to read on the getOutputData method. After reading each frame, you simply merge the Mat objects into a single Mat.

    I wrote this code to get the whole volume:

    DicomImage *image = new DicomImage(file);
    
    // Get the information
    unsigned int nRows = image->getHeight();
    unsigned int nCols = image->getWidth();
    unsigned int nImgs = image->getFrameCount();
    
    vector <Mat> slices(nImgs);
    
    // Loop for each slice
    for(int k = 0; k<nImgs; k++){
    
        (Uint16 *) pixelData = (Uint16 *)(image->getOutputData(16 /* bits */,k /* slice */));
    
        slices[k] = Mat(nRows, nCols, CV_16U, pixelData).clone();
    
    }
    
    Mat img;
    
    // Merge the slices in a single img
    merge(slices,img);
    
    cout << img.size() << endl;
    cout << img.channels() << endl;
    
    // Output:
    // [512 x 512]
    // 5