Search code examples
c#pixeldicomclearcanvas

Dicom image window and level problems (sometimes)


I am making an image viewer using the c# ClearCanvas libraries, and I am trying to display images with their stored window center and window width values applied to the image. To do this, I read the window center, window width, and raw pixel data from the Dicom file which I convert to a byte array and then use the following code to apply the window settings:

 int lower_bound = window_center - window_width / 2;
 int upper_bound = window_center + window_width / 2;



            //copy matrix and do window caluclations
            float[] wlpixels = new float[pixels.Length];
            for (int i = 0; i < w * h; i++)
            {

                if (pixels[i] <= lower_bound)
                    wlpixels[i] = 0;
                else if (pixels[i] > upper_bound)
                    wlpixels[i] = 255;
                else
                {
                    wlpixels[i] = ((pixels[i] - lower_bound) / window_width) * 255;


                }
            }

This has worked like a charm for some images while others, specifically with low or negative window center values, display incorrectly. They display with an abundance of white pixels that aren't supposed to be white.

Am I doing my window/level calculations correctly? If not, how do I do them correctly? If so, what else do I need to do to make this work with all scenarios?


Solution

  • So I ended up using Clear Canvas's drawToBitmap() function to display the image (which I used before but scratched because it wasn't applying the window settings). Turns out, in order to make it account for the window settings you need to include the line

    using ClearCanvas.ImageViewer.Tools.Standard;
    

    And then to display the image using drawToBitmap() you use code similar to the following:

    DicomFile dcm = new DicomFile();
    dcm.Load("filename");
    LocalSopDataSource lsds = new LocalSopDataSource(dcm);
    ImageSop sop = new ImageSop(lsds);
    Frame frame = sop.Frames[1];
    IPresentationImage pres = PresentationImageFactory.Create(frame);
    bitmap = pres.DrawToBitmap(frame.Columns, frame.Rows);
    

    I've tested this with Dicom images that have no raw pixel data in them and it works as well (no clue why)... So yeah, if you're using Clear Canvas this is the way to go.

    I still ended up copying the pixels from this bitmap to another matrix to do window center/width changes via sliders and stuff, but to get the image this is what you should use.