Example #1
0
        public static DicomPixelData CreateColorData(int width, int height)
        {
            var dataset = new DicomDataset();

            dataset.Add <ushort>(DicomTag.Columns, (ushort)width)

            .Add <ushort>(DicomTag.Rows, (ushort)height)

            .Add <ushort>(DicomTag.BitsAllocated, 8)

            .Add <ushort>(DicomTag.BitsStored, 8)

            .Add <ushort>(DicomTag.HighBit, 7)

            .Add(DicomTag.PixelRepresentation, (ushort)PixelRepresentation.Unsigned)

            .Add(DicomTag.PlanarConfiguration, (ushort)PlanarConfiguration.Interleaved)

            .Add <ushort>(DicomTag.SamplesPerPixel, 3)

            .Add(DicomTag.PhotometricInterpretation, PhotometricInterpretation.Monochrome2.Value);

            var pixelData = DicomPixelData.Create(dataset, true);

            return(pixelData);
        }
Example #2
0
        private void ReadInlineBinary
        (
            DicomTag tag,
            DicomVR vr,
            JsonTextReader reader,
            DicomDataset dataset,
            int level
        )
        {
            if (reader.Read( ))
            {
                Dicom.IO.Buffer.MemoryByteBuffer buffer = null;
                string base64 = (string)reader.Value;


                if (!string.IsNullOrEmpty(base64))
                {
                    buffer = new Dicom.IO.Buffer.MemoryByteBuffer(System.Convert.FromBase64String(base64));
                }

                if (tag == DicomTag.PixelData && level == 0)
                {
                    var pixelData = DicomPixelData.Create(dataset, true);  //2nd parameter is true since we are adding new data here

                    pixelData.AddFrame(buffer);
                }
                else
                {
                    dataset.AddOrUpdate <Dicom.IO.Buffer.IByteBuffer> (vr, tag, buffer);
                }
            }
        }
        static private void BreakUp()
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            const string   sourcePath = "/media/nikolaev_ov/CEFE3C54FE3C36D5/DICOM/ComputerTomography/Covid/favorite/several-frames/sources/1.2.392.200036.9116.2.5.1.37.2418295482.1507184833.33568";
            DicomFile      dicomFile  = DicomFile.Open(sourcePath);
            DicomPixelData pixelData  = DicomPixelData.Create(dicomFile.Dataset, false);

            MemoryStream[] frameFiles = new MemoryStream[pixelData.NumberOfFrames];
            MemoryStream   zip        = new MemoryStream();

            using (ZipArchive archive = new ZipArchive(zip, ZipArchiveMode.Create, true))
            {
                for (int frameIndex = 0; frameIndex != pixelData.NumberOfFrames; frameIndex++)
                {
                    DicomDataset frameDataset = new DicomDataset(dicomFile.Dataset.InternalTransferSyntax);
                    dicomFile.Dataset.CopyTo(frameDataset);
                    DicomPixelData framePixelData = DicomPixelData.Create(frameDataset, true);
                    IByteBuffer    buffer         = pixelData.GetFrame(frameIndex);
                    framePixelData.AddFrame(buffer);
                    ZipArchiveEntry readmeEntry = archive.CreateEntry(frameIndex.ToString());
                    using (Stream stream = readmeEntry.Open())
                        new DicomFile(frameDataset).Save(stream);
                }
            }
            stopwatch.Stop();
            Console.WriteLine(stopwatch.ElapsedMilliseconds);
            using (FileStream file = new FileStream("/media/nikolaev_ov/CEFE3C54FE3C36D5/test.zip", FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                zip.Position = 0;
                zip.CopyTo(file);
            }
        }
Example #4
0
        public static void Run()
        {
            string     filename = @"D:\Dicom\1.1.dcm";
            DicomFile  file     = DicomFile.Open(filename);
            DicomImage image    = new DicomImage(file.Dataset);
            //var img = image.RenderImage();
            //PinnedIntArray array = img.Pixels;
            //Console.WriteLine(array.Count/512);
            var pixelData = DicomPixelData.Create(file.Dataset);

            //foreach (var item in typeof(DicomPixelData).GetProperties())
            //{
            //    Console.WriteLine($"{item.Name}, {item.GetValue(pixelData)}");
            //}
            Console.WriteLine($"{image.WindowCenter}, {image.WindowWidth}");
            var img = image.RenderImage();

            img.Render(0, false, false, 90);


            Console.WriteLine(pixelData.GetType());
            var newBuffer = CreateBuffer(pixelData);

            var newData = DicomPixelData.Create(file.Dataset, true);

            newData.AddFrame(newBuffer);

            var data2 = DicomPixelData.Create(file.Dataset);

            Console.WriteLine(data2.NumberOfFrames);

            file.Save("D:\\2.dcm");
        }
Example #5
0
        private void ReadBulkData
        (
            DicomTag tag,
            DicomVR vr,
            JsonTextReader reader,
            DicomDataset dataset,
            int level
        )
        {
            Dicom.IO.Buffer.BulkDataUriByteBuffer data = null;


            if (reader.Read( ))
            {
                string uri = (string)reader.Value;


                if (!string.IsNullOrEmpty(uri))
                {
                    data = new Dicom.IO.Buffer.BulkDataUriByteBuffer(uri);
                }

                if (tag == DicomTag.PixelData && level == 0)
                {
                    var pixelData = DicomPixelData.Create(dataset, true); //2nd parameter is true since we are adding new data here
                    pixelData.AddFrame(data);
                }
                else
                {
                    dataset.AddOrUpdate <Dicom.IO.Buffer.IByteBuffer> (vr, tag, data);
                }
            }
        }
        public void ExportImage(Bitmap bitmap)
        {
            bitmap = GetValidImage(bitmap);
            int rows, columns;

            byte[]           pixels  = GetPixels(bitmap, out rows, out columns);
            MemoryByteBuffer buffer  = new MemoryByteBuffer(pixels);
            DicomDataset     dataset = new DicomDataset();

            FillDataset(dataset);
            dataset.Add(DicomTag.PhotometricInterpretation, PhotometricInterpretation.Rgb.Value);
            dataset.Add(DicomTag.Rows, (ushort)rows);
            dataset.Add(DicomTag.Columns, (ushort)columns);
            dataset.AddOrUpdate(DicomTag.BitsAllocated, (ushort)8);
            DicomPixelData pixelData = DicomPixelData.Create(dataset, true);

            pixelData.BitsStored          = 8;
            pixelData.BitsAllocated       = 8;
            pixelData.SamplesPerPixel     = 3;
            pixelData.HighBit             = 7;
            pixelData.PixelRepresentation = 0;
            pixelData.PlanarConfiguration = 0;
            pixelData.AddFrame(buffer);

            DicomFile dicomfile = new DicomFile(dataset);

            dicomfile.Save("dicomfile.dcm");
        }
        static internal unsafe void Start(string[] args)
        {
            const string rootDirectory            = "/media/nikolaev_ov/CEFE3C54FE3C36D5/DICOM";
            const string targetDirectionDirectory = "favorite";

            foreach (var direction in new[] { "Mammography", "Fluorography", "ComputerTomography/Covid", "ComputerTomography/Cancer" })
            {
                foreach (var directory in Directory.GetDirectories(Path.Combine(rootDirectory, direction, targetDirectionDirectory)))
                {
                    var sourceDirectory         = Path.Combine(directory, "sources");
                    var noPixelDataDirectory    = Path.Combine(directory, "no-pixel-data");
                    var emptyPixelDataDirectory = Path.Combine(directory, "empty-pixel-data");
                    var filePaths = Directory.GetFiles(sourceDirectory);
                    foreach (var sourceFilePath in filePaths)
                    {
                        string fileName = Path.GetFileName(sourceFilePath);

                        DicomFile file;
                        try { file = DicomFile.Open(sourceFilePath); }
                        catch { continue; }
                        if (file == null)
                        {
                            continue;
                        }

                        file.Dataset.Remove(DicomTag.PixelData);
                        SaveDicomFile(file, noPixelDataDirectory, fileName);

                        var pixelData = DicomPixelData.Create(file.Dataset, true);
                        SaveDicomFile(file, emptyPixelDataDirectory, fileName);
                    }
                }
            }
        }
Example #8
0
        public DicomFile GetDicom(Image <Gray, byte> outputImage, DicomInformation dicomInformation)
        {
            var bitmap = outputImage.Bitmap;

            bitmap = GetValidImage(bitmap);

            int rows, columns;

            byte[] pixels = GetPixels(bitmap, out rows, out columns);

            MemoryByteBuffer buffer = new MemoryByteBuffer(pixels);

            DicomDataset dataset = new DicomDataset();

            FillDataset(dataset, dicomInformation);

            dataset.Add(DicomTag.PhotometricInterpretation, PhotometricInterpretation.Rgb.Value);
            dataset.Add(DicomTag.Rows, (ushort)rows);
            dataset.Add(DicomTag.Columns, (ushort)columns);
            dataset.Add(DicomTag.BitsAllocated, (ushort)8);

            DicomPixelData pixelData = DicomPixelData.Create(dataset, true);

            pixelData.BitsStored          = 8;
            pixelData.BitsAllocated       = 8;
            pixelData.SamplesPerPixel     = 3;
            pixelData.HighBit             = 7;
            pixelData.PixelRepresentation = 0;
            pixelData.PlanarConfiguration = 0;
            pixelData.AddFrame(buffer);

            DicomFile dicomfile = new DicomFile(dataset);

            return(dicomfile);
        }
Example #9
0
        /// <summary>
        /// The GetDicomFileByRaw.
        /// </summary>
        /// <param name="pixels">The pixels<see cref="byte[]"/>.</param>
        /// <param name="Heigh">The Heigh<see cref="int"/>.</param>
        /// <param name="width">The width<see cref="int"/>.</param>
        /// <returns>The <see cref="DicomFile"/>.</returns>
        public static DicomFile GetDicomFileByRaw(byte[] pixels, int Heigh, int width)
        {
            MemoryByteBuffer buffer  = new MemoryByteBuffer(pixels);
            DicomDataset     dataset = new DicomDataset();

            //FillDataset(dataset);
            dataset.AddOrUpdate(DicomTag.PhotometricInterpretation, PhotometricInterpretation.Monochrome2.Value);
            // dataset.Add(DicomTag.PhotometricInterpretation, PhotometricInterpretation.Monochrome2.ToString());
            dataset.AddOrUpdate(DicomTag.Rows, (ushort)Heigh);
            dataset.AddOrUpdate(DicomTag.Columns, (ushort)width);

            dataset.AddOrUpdate(DicomTag.BitsAllocated, (ushort)16);
            dataset.AddOrUpdate(DicomTag.SOPClassUID, "1.2.840.10008.5.1.4.1.1.2");
            dataset.Add(DicomTag.SOPInstanceUID, "1.2.840.10008.5.1.4.1.1.2.20181120090837121314");
            DicomPixelData pixelData = DicomPixelData.Create(dataset, true);

            pixelData.BitsStored = 16;
            //pixelData.BitsAllocated = 8;
            pixelData.SamplesPerPixel     = pixelData.HighBit = 15;
            pixelData.PixelRepresentation = 0;
            pixelData.PlanarConfiguration = 0;
            pixelData.AddFrame(buffer);

            DicomFile dicomfile = new DicomFile(dataset);

            //   dicomfile.Save(@"C:\Users\admin\Pictures\Saved Pictures\" + System.DateTime.Now.ToString("FFFF")); ;
            return(dicomfile);
        }
Example #10
0
        static DicomFile CreatDicomFileNoDicomImage(DicomFile dicomFile)
        {
            byte[] temp = new byte[512 * 512];
            dicomFile.Dataset.AddOrUpdate(DicomTag.Rows, (ushort)512);
            dicomFile.Dataset.AddOrUpdate(DicomTag.Columns, (ushort)512);
            dicomFile.Dataset.AddOrUpdate(DicomTag.BitsAllocated, (ushort)16);
            dicomFile.Dataset.TryGetString(DicomTag.SOPInstanceUID, out string str);
            if (str == null)
            {
                dicomFile.Dataset.Add(DicomTag.SOPInstanceUID, "1.1.1.1.1.1");
            }

            MemoryByteBuffer buffer    = new MemoryByteBuffer(temp);
            DicomPixelData   pixelData = DicomPixelData.Create(dicomFile.Dataset, true);

            pixelData.BitsStored = 16;
            //pixelData.BitsAllocated = 8;
            pixelData.SamplesPerPixel     = pixelData.HighBit = 15;
            pixelData.PixelRepresentation = 0;
            pixelData.PlanarConfiguration = 0;
            pixelData.AddFrame(buffer);

            dicomFile = new DicomFile(dicomFile.Dataset);
            return(dicomFile);
        }
Example #11
0
        public static void SaveToDICOMFile(short[] pixels,int noRows,int noCols,string fileName)
        {
            DicomDataset dataset = new DicomDataset();
            byte[] buf = new byte[2*noCols*noRows];
            Buffer.BlockCopy(pixels, 0, buf, 0, 2 * noCols * noRows);
            FillDataset(dataset);
            dataset.Add(DicomTag.PixelAspectRatio, noRows.ToString()+"\\"+noCols.ToString());
            dataset.Add(DicomTag.PhotometricInterpretation, PhotometricInterpretation.Monochrome2.Value);
            dataset.Add(DicomTag.Rows, (ushort)noRows);
            dataset.Add(DicomTag.Columns, (ushort)noCols);
            dataset.Add(DicomTag.BitsStored, (ushort)16);
            dataset.Add(DicomTag.BitsAllocated, (ushort)16);
            dataset.Add(DicomTag.HighBit, (ushort)15);
            DicomPixelData pixelData = DicomPixelData.Create(dataset, true);
            pixelData.BitsStored = 16;
            //pixelData.BitsAllocated = 16;
            pixelData.SamplesPerPixel = 1;
            pixelData.HighBit = 15;
            pixelData.PixelRepresentation = PixelRepresentation.Unsigned;
            pixelData.PlanarConfiguration = 0;
            MemoryByteBuffer pixelsInBytes = new MemoryByteBuffer(buf);
            pixelData.AddFrame(pixelsInBytes);

            DicomFile dicomfile = new DicomFile(dataset);
            dicomfile.Save(fileName);
        }
Example #12
0
        private static DicomDataset Decode(
            DicomDataset oldDataset,
            DicomTransferSyntax outSyntax,
            IDicomCodec codec,
            DicomCodecParams parameters)
        {
            if (codec == null)
            {
                throw new DicomCodecException("Decoding dataset with transfer syntax: {0} is not supported. See here to get help resolving the reason: https://github.com/fo-dicom/fo-dicom/wiki/Native-codecs-on-.NET",
                                              oldDataset.InternalTransferSyntax);
            }

            var oldPixelData = DicomPixelData.Create(oldDataset);

            var newDataset = oldDataset.Clone();

            newDataset.InternalTransferSyntax = outSyntax;
            var newPixelData = DicomPixelData.Create(newDataset, true);

            codec.Decode(oldPixelData, newPixelData, parameters);

            ProcessOverlays(oldDataset, newDataset);

            newDataset.RecalculateGroupLengths(false);

            return(newDataset);
        }
        private Boolean IsDcomFileValid(Stream dcomStream)
        {
            DicomFile f;

            try
            {
                f = DicomFile.Open(dcomStream);
            }
            catch (DicomFileException)
            {
                return(false);
            }
            catch (DicomReaderException)
            {
                return(false);
            }

            if (f == null)
            {
                return(false);
            }
            if (!f.Dataset.GetString(DicomTag.PhotometricInterpretation).Contains("MONOCHROME"))
            {
                return(false);
            }
            if (DicomPixelData.Create(f.Dataset).BitDepth.BitsStored != 16)
            {
                return(false);
            }
            return(true);
        }
Example #14
0
        public void EncodeDecodeRLE16()
        {
            var files = Directory.GetFiles(@"Test Data");

            foreach (var testFile in files)
            {
                try
                {
                    var       myOriginalDicomFilePath = testFile;
                    DicomFile myOriginalDicomFile     = DicomFile.Open(myOriginalDicomFilePath);
                    DicomFile myNewFile = myOriginalDicomFile.Clone(DicomTransferSyntax.RLELossless);
                    DicomFile myResFile = myNewFile.Clone(myOriginalDicomFile.Dataset.InternalTransferSyntax);

                    // Supporting 16bit encoded images
                    var myBitsAllocated = myResFile.Dataset.GetSingleValue <ushort>(DicomTag.BitsAllocated);
                    if (myBitsAllocated == 16)
                    {
                        byte[] myOriginalBytes = DicomPixelData.Create(myOriginalDicomFile.Dataset).GetFrame(0).Data;
                        byte[] myResBytes      = DicomPixelData.Create(myResFile.Dataset).GetFrame(0).Data;

                        if (!myOriginalBytes.SequenceEqual(myResBytes))
                        {
                            // Number of different bytes
                            int myDiffCount = myResBytes.Where((inT, inI) => inT != myOriginalBytes[inI]).Count();
                            Assert.Equal(0, myDiffCount);
                            Trace.WriteLine("Diff count " + myDiffCount);

                            // Run through all image
                            for (var myIndex = 0; myIndex < myOriginalBytes.Length; myIndex += 2)
                            {
                                // Get Pixel value from Original image
                                byte   myOriginalByte1      = myOriginalBytes[myIndex];
                                byte   myOrginalByte2       = myOriginalBytes[myIndex + 1];
                                ushort myOriginalPixelValue =
                                    BitConverter.ToUInt16(new byte[] { myOriginalByte1, myOrginalByte2 }, 0);

                                // Get Pixel value from RoundTrip image
                                byte   myResByte1      = myResBytes[myIndex];
                                byte   myResByte2      = myResBytes[myIndex + 1];
                                ushort myResPixelValue = BitConverter.ToUInt16(new byte[] { myResByte1, myResByte2 }, 0);

                                // If Value are different
                                if (myOriginalPixelValue != myResPixelValue)
                                {
                                    Trace.Write("Diff:" + Math.Abs(myOriginalPixelValue - myResPixelValue));
                                    Trace.Write(
                                        $" Original Value: {myOriginalPixelValue} ({myOriginalByte1}, {myOrginalByte2})");
                                    Trace.WriteLine($" Res Value: {myResPixelValue} ({myResByte1}, {myResByte2})");
                                    break;
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    // ignore
                }
            }
        }
Example #15
0
        public async Task GivenUnsupportedTransferSyntax_WhenRetrieveFrameWithOriginalTransferSyntax_ThenOriginalContentReturned()
        {
            var studyInstanceUid  = TestUidGenerator.Generate();
            var seriesInstanceUid = TestUidGenerator.Generate();
            var sopInstanceUid    = TestUidGenerator.Generate();

            DicomFile dicomFile = Samples.CreateRandomDicomFileWith8BitPixelData(
                studyInstanceUid,
                seriesInstanceUid,
                sopInstanceUid,
                transferSyntax: DicomTransferSyntax.HEVCH265Main10ProfileLevel51.UID.UID,
                encode: false);

            await InternalStoreAsync(new[] { dicomFile });

            // Check for series
            DicomWebResponse <IReadOnlyList <Stream> > response = await _client.RetrieveFramesAsync(
                studyInstanceUid,
                seriesInstanceUid,
                sopInstanceUid,
                dicomTransferSyntax : "*",
                frames : new[] { 1 });

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(response.Value[0].ToByteArray(), DicomPixelData.Create(dicomFile.Dataset).GetFrame(0).Data);
        }
Example #16
0
        private DicomDataset Encode(DicomDataset oldDataset, DicomTransferSyntax inSyntax, IDicomCodec codec, DicomCodecParams parameters)
        {
            DicomPixelData oldPixelData = DicomPixelData.Create(oldDataset, false);

            DicomDataset newDataset = oldDataset.Clone();

            newDataset.InternalTransferSyntax = codec.TransferSyntax;
            DicomPixelData newPixelData = DicomPixelData.Create(newDataset, true);

            codec.Encode(oldPixelData, newPixelData, parameters);

            if (codec.TransferSyntax.IsLossy && newPixelData.NumberOfFrames > 0)
            {
                newDataset.Add(new DicomCodeString(DicomTag.LossyImageCompression, "01"));

                List <string> methods = new List <string>();
                if (newDataset.Contains(DicomTag.LossyImageCompressionMethod))
                {
                    methods.AddRange(newDataset.Get <string[]>(DicomTag.LossyImageCompressionMethod));
                }
                methods.Add(codec.TransferSyntax.LossyCompressionMethod);
                newDataset.Add(new DicomCodeString(DicomTag.LossyImageCompressionMethod, methods.ToArray()));

                double oldSize = oldPixelData.GetFrame(0).Size;
                double newSize = newPixelData.GetFrame(0).Size;
                string ratio   = String.Format("{0:0.000}", oldSize / newSize);
                newDataset.Add(new DicomDecimalString(DicomTag.LossyImageCompressionRatio, ratio));
            }

            ProcessOverlays(oldDataset, newDataset);

            newDataset.RecalculateGroupLengths(false);

            return(newDataset);
        }
Example #17
0
        public static void ImportImage()
        {
            Bitmap bitmap = new Bitmap(@"C:\Users\ryan.chang\Desktop\output\testabc.bmp");            //bitmap = GetValidImage(bitmap);


            byte[]           pixels  = GetPixels(bitmap);
            MemoryByteBuffer buffer  = new MemoryByteBuffer(pixels);
            DicomDataset     dataset = new DicomDataset();        //FillDataset(dataset);

            dataset.Add(DicomTag.PhotometricInterpretation, PhotometricInterpretation.Rgb.Value);
            dataset.Add(DicomTag.Rows, (ushort)bitmap.Height);
            dataset.Add(DicomTag.Columns, (ushort)bitmap.Width);
            dataset.Add(DicomTag.BitsAllocated, (ushort)8);
            dataset.Add(DicomTag.SOPClassUID, "1.2.840.10008.5.1.4.1.1.7");
            dataset.Add(DicomTag.StudyInstanceUID, "1.2.840.10008.5.1.4.1.1.2.20181120090837121311");
            dataset.Add(DicomTag.SeriesInstanceUID, "1.2.840.10008.5.1.4.1.1.2.20181120090837121312");
            dataset.Add(DicomTag.SOPInstanceUID, "1.2.840.10008.5.1.4.1.1.2.20181120090837121314");
            dataset.Add(DicomTag.TransferSyntaxUID, "1.2.840.10008.1.2.4.70");

            //dataset.Add(DicomTag.SpecificCharacterSet, "ISO_IR 192");
            //dataset.Add(new DicomPersonName(DicomTag.PatientName,Encoding.UTF8,"王曉明"));
            DicomPixelData pixelData = DicomPixelData.Create(dataset, true);

            pixelData.BitsStored          = 8;   //pixelData.BitsAllocated = 8;
            pixelData.SamplesPerPixel     = 3;
            pixelData.HighBit             = 7;
            pixelData.PixelRepresentation = 0;
            pixelData.PlanarConfiguration = 0;
            pixelData.AddFrame(buffer);

            DicomFile dicomfile = new DicomFile(dataset);

            dicomfile.Save(@"C:\Users\ryan.chang\Desktop\output\dicomfile.dcm");
        }
Example #18
0
        internal void DrawBlackBoxWithWhiteText(DicomDataset ds, int width, int height, string msg)
        {
            var bitmap = new Bitmap(500, 500);

            using (var g = Graphics.FromImage(bitmap))
            {
                g.FillRectangle(blackBrush, 0, 0, width, height);
                g.DrawString(msg, new Font(FontFamily.GenericMonospace, 12), whiteBrush, 250, 100);
            }

            byte[]           pixels = GetPixels(bitmap, out int rows, out int columns);
            MemoryByteBuffer buffer = new MemoryByteBuffer(pixels);

            ds.Add(DicomTag.PhotometricInterpretation, PhotometricInterpretation.Rgb.Value);
            ds.Add(DicomTag.Rows, (ushort)rows);
            ds.Add(DicomTag.Columns, (ushort)columns);
            ds.Add(DicomTag.BitsAllocated, (ushort)8);

            DicomPixelData pixelData = DicomPixelData.Create(ds, true);

            pixelData.BitsStored          = 8;
            pixelData.SamplesPerPixel     = 3;
            pixelData.HighBit             = 7;
            pixelData.PixelRepresentation = 0;
            pixelData.PlanarConfiguration = 0;
            pixelData.AddFrame(buffer);
        }
Example #19
0
 private static IPixelData CreatePixelData_ <T>(
     T[] data,
     ushort bitsAllocated,
     ushort bitsStored,
     ushort highBit,
     ushort pixelRepresentation,
     Func <T, byte[]> getBytes)
 {
     return
         (PixelDataFactory.Create(
              DicomPixelData.Create(
                  new DicomDataset
     {
         {
             DicomTag.PhotometricInterpretation,
             PhotometricInterpretation.Monochrome1.Value
         },
         { DicomTag.BitsAllocated, bitsAllocated },
         { DicomTag.BitsStored, bitsStored },
         { DicomTag.HighBit, highBit },
         { DicomTag.PixelData, data.SelectMany(getBytes).ToArray() },
         { DicomTag.PixelRepresentation, pixelRepresentation },
         { DicomTag.Columns, (ushort)1 },
         { DicomTag.Rows, (ushort)data.Length }
     }),
              0));
 }
        /// <summary>
        /// Composes the given images into single multiframe Dicom image. Images has to be from the same study with the same attributes.
        /// </summary>
        /// <param name="images">RawImage to be composed</param>
        /// <exception cref="ArgumentNullException"><paramref name="images"/> is null</exception>
        /// <exception cref="ArgumentException"><paramref name="images"/> is empty</exception>
        /// <returns>Multiframe Dicom image containing all the input images</returns>
        private DicomImage ComposeImages(IList <DicomImage> images)
        {
            if (images == null)
            {
                throw new ArgumentNullException(nameof(images));
            }

            if (images.Count == 0)
            {
                throw new ArgumentException("Collection is empty", nameof(images));
            }

            var sorted = SortInputImages(images);

            var baseImage   = sorted.First();
            var baseDataSet = baseImage.Dataset;

            var baseFrame = baseImage.PixelData.GetFrame(0);
            var pixelData = DicomPixelData.Create(baseDataSet, true);

            pixelData.AddFrame(baseFrame);

            foreach (var image in sorted.Skip(1))
            {
                var data = image.PixelData.GetFrame(0).Data;
                pixelData.AddFrame(new MemoryByteBuffer(data));
            }

            return(new DicomImage(baseDataSet));
        }
Example #21
0
        public async Task GivenUnsupportedTransferSyntax_WhenRetrieveFrameWithOriginalTransferSyntax_ThenOriginalContentReturned()
        {
            var studyInstanceUid  = TestUidGenerator.Generate();
            var seriesInstanceUid = TestUidGenerator.Generate();
            var sopInstanceUid    = TestUidGenerator.Generate();

            DicomFile dicomFile = Samples.CreateRandomDicomFileWith8BitPixelData(
                studyInstanceUid,
                seriesInstanceUid,
                sopInstanceUid,
                transferSyntax: DicomTransferSyntax.HEVCH265Main10ProfileLevel51.UID.UID,
                encode: false);

            await InternalStoreAsync(new[] { dicomFile });

            // Check for series
            using DicomWebAsyncEnumerableResponse <Stream> response = await _client.RetrieveFramesAsync(
                      studyInstanceUid,
                      seriesInstanceUid,
                      sopInstanceUid,
                      dicomTransferSyntax : "*",
                      frames : new[] { 1 });

            Stream[] results = await response.ToArrayAsync();

            Assert.Collection(
                results,
                item => Assert.Equal(item.ToByteArray(), DicomPixelData.Create(dicomFile.Dataset).GetFrame(0).Data));
        }
Example #22
0
        public static void AppendRandomPixelData(int rows, int columns, int frames, params DicomFile[] dicomFiles)
        {
            EnsureArg.IsGte(rows, 0, nameof(rows));
            EnsureArg.IsGte(columns, 0, nameof(columns));
            EnsureArg.IsNotNull(dicomFiles, nameof(dicomFiles));

            var          pixelDataSize = rows * columns;
            const ushort bitsAllocated = 8;

            dicomFiles.Each(x =>
            {
                x.Dataset.AddOrUpdate(DicomTag.Rows, (ushort)rows);
                x.Dataset.AddOrUpdate(DicomTag.Columns, (ushort)columns);
                x.Dataset.AddOrUpdate(DicomTag.BitsAllocated, bitsAllocated);

                var pixelData                 = DicomPixelData.Create(x.Dataset, true);
                pixelData.SamplesPerPixel     = 1;
                pixelData.PixelRepresentation = PixelRepresentation.Unsigned;
                pixelData.BitsStored          = bitsAllocated;
                pixelData.HighBit             = bitsAllocated - 1;

                for (var i = 0; i < frames; i++)
                {
                    pixelData.AddFrame(CreateRandomPixelData(pixelDataSize));
                }
            });
        }
Example #23
0
        public async Task GivenMultipleFrames_WhenRetrieveFrame_ThenServerShouldReturnExpectedContent()
        {
            string studyInstanceUid = TestUidGenerator.Generate();

            DicomFile          dicomFile1    = Samples.CreateRandomDicomFileWithPixelData(studyInstanceUid, frames: 3);
            DicomPixelData     pixelData     = DicomPixelData.Create(dicomFile1.Dataset);
            InstanceIdentifier dicomInstance = dicomFile1.Dataset.ToInstanceIdentifier();

            await InternalStoreAsync(new[] { dicomFile1 });

            using DicomWebAsyncEnumerableResponse <Stream> response = await _client.RetrieveFramesAsync(
                      dicomInstance.StudyInstanceUid,
                      dicomInstance.SeriesInstanceUid,
                      dicomInstance.SopInstanceUid,
                      frames : new[] { 1, 2 },
                      dicomTransferSyntax : "*");

            Stream[] frames = await response.ToArrayAsync();

            Assert.NotNull(frames);
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(2, frames.Length);
            Assert.Equal(KnownContentTypes.MultipartRelated, response.ContentHeaders.ContentType.MediaType);
            Assert.Equal(pixelData.GetFrame(0).Data, frames[0].ToByteArray());
            Assert.Equal(pixelData.GetFrame(1).Data, frames[1].ToByteArray());
        }
Example #24
0
        public async Task GivenSupportedAcceptHeaders_WhenRetrieveFrame_ThenServerShouldReturnExpectedContent(string testDataFolder, string mediaType, string transferSyntax)
        {
            TranscoderTestData transcoderTestData = TranscoderTestDataHelper.GetTestData(testDataFolder);
            DicomFile          inputDicomFile     = await DicomFile.OpenAsync(transcoderTestData.InputDicomFile);

            await EnsureFileIsStoredAsync(inputDicomFile);

            var instanceId = inputDicomFile.Dataset.ToInstanceIdentifier();

            _studiesToClean.Add(instanceId.StudyInstanceUid);

            DicomFile      outputDicomFile = DicomFile.Open(transcoderTestData.ExpectedOutputDicomFile);
            DicomPixelData pixelData       = DicomPixelData.Create(outputDicomFile.Dataset);

            using DicomWebAsyncEnumerableResponse <Stream> response = await _client.RetrieveFramesAsync(
                      instanceId.StudyInstanceUid,
                      instanceId.SeriesInstanceUid,
                      instanceId.SopInstanceUid,
                      mediaType,
                      transferSyntax,
                      frames : new[] { 1 });

            int frameIndex = 0;

            await foreach (Stream item in response)
            {
                // TODO: verify media type once https://microsofthealth.visualstudio.com/Health/_workitems/edit/75185 is done
                Assert.Equal(item.ToByteArray(), pixelData.GetFrame(frameIndex).Data);
                frameIndex++;
            }
        }
Example #25
0
        private static DicomDataset Decode(
            DicomDataset oldDataset,
            DicomTransferSyntax outSyntax,
            IDicomCodec codec,
            DicomCodecParams parameters)
        {
            if (codec == null)
            {
                throw new DicomCodecException("Decoding dataset with transfer syntax: {0} is not supported.",
                                              oldDataset.InternalTransferSyntax);
            }

            var oldPixelData = DicomPixelData.Create(oldDataset);

            var newDataset = oldDataset.Clone();

            newDataset.InternalTransferSyntax = outSyntax;
            var newPixelData = DicomPixelData.Create(newDataset, true);

            codec.Decode(oldPixelData, newPixelData, parameters);

            ProcessOverlays(oldDataset, newDataset);

            newDataset.RecalculateGroupLengths(false);

            return(newDataset);
        }
Example #26
0
        public void DicomPixelDataCreate_NewPixelDataFromOldFragmentedFile_ReproducesData()
        {
            ImageManager.SetImplementation(WinFormsImageManager.Instance);

            var oldFile = DicomFile.Open(@"Test Data\D_CLUNIE_CT1_RLE_FRAGS.dcm");
            var newFile = oldFile.Clone();

            var oldPixelData = DicomPixelData.Create(oldFile.Dataset);
            var newPixelData = DicomPixelData.Create(newFile.Dataset, true);

            Assert.Equal(oldFile.Dataset.InternalTransferSyntax, newPixelData.Syntax);

            var oldBuffer = oldPixelData.GetFrame(0);

            Assert.IsType <CompositeByteBuffer>(oldBuffer);

            newPixelData.AddFrame(oldBuffer);

            var height = oldPixelData.Height;
            var width  = oldPixelData.Width;

            using (var oldImage = new DicomImage(oldFile.Dataset).RenderImage().AsBitmap())
                using (var newImage = new DicomImage(newFile.Dataset).RenderImage().AsBitmap())
                {
                    for (var j = 0; j < height; ++j)
                    {
                        for (var i = 0; i < width; ++i)
                        {
                            Assert.Equal(oldImage.GetPixel(i, j), newImage.GetPixel(i, j));
                        }
                    }
                }

            newFile.Save("GH553.dcm");
        }
Example #27
0
        public async Task GivenStoredInstancesWithFrames_WhenRetrieveRequestForFrames_ThenFramesInInstanceAreRetrievedSuccesfully()
        {
            // Add multiple instances to validate that we return the requested instance and ignore the other(s).
            List <VersionedInstanceIdentifier> versionedInstanceIdentifiers = SetupInstanceIdentifiersList(ResourceType.Frames);
            var framesToRequest = new List <int> {
                1, 2
            };

            // For the first instance identifier, set up the fileStore to return a stream containing a file associated with the identifier.
            KeyValuePair <DicomFile, Stream> streamAndStoredFile = StreamAndStoredFileFromDataset(GenerateDatasetsFromIdentifiers(versionedInstanceIdentifiers.First()), frames: 3).Result;

            _fileStore.GetFileAsync(versionedInstanceIdentifiers.First(), DefaultCancellationToken).Returns(streamAndStoredFile.Value);

            // Setup frame handler to return the frames as streams from the file.
            Stream[] frames = framesToRequest.Select(f => GetFrameFromFile(streamAndStoredFile.Key.Dataset, f)).ToArray();
            var      retrieveResourceRequest = new RetrieveResourceRequest(_studyInstanceUid, _firstSeriesInstanceUid, _sopInstanceUid, framesToRequest, new[] { AcceptHeaderHelpers.CreateAcceptHeaderForGetFrame() });

            _dicomFrameHandler.GetFramesResourceAsync(streamAndStoredFile.Value, retrieveResourceRequest.Frames, true, "*").Returns(frames);

            RetrieveResourceResponse response = await _retrieveResourceService.GetInstanceResourceAsync(
                retrieveResourceRequest,
                DefaultCancellationToken);

            // Validate response status code and ensure response streams has expected frames - it should be equivalent to what the store was set up to return.
            AssertPixelDataEqual(DicomPixelData.Create(streamAndStoredFile.Key.Dataset).GetFrame(framesToRequest[0]), response.ResponseStreams.ToList()[0]);
            AssertPixelDataEqual(DicomPixelData.Create(streamAndStoredFile.Key.Dataset).GetFrame(framesToRequest[1]), response.ResponseStreams.ToList()[1]);

            streamAndStoredFile.Value.Dispose();
        }
Example #28
0
        private void AddColorImage(Bitmap bitmap, int index)
        {
            if (_currentFilmBox == null)
            {
                throw new InvalidOperationException("Start film box first!");
            }
            if (index < 0 || index > _currentFilmBox.BasicImageBoxes.Count)
            {
                // ReSharper disable once NotResolvedInText
                throw new ArgumentOutOfRangeException("Image box index out of range");
            }

            if (bitmap.PixelFormat != PixelFormat.Format24bppRgb &&
                bitmap.PixelFormat != PixelFormat.Format32bppArgb &&
                bitmap.PixelFormat != PixelFormat.Format32bppRgb
                )
            {
                throw new ArgumentException("Not supported bitmap format");
            }

            var dataset = new DicomDataset
            {
                { DicomTag.Columns, (ushort)bitmap.Width },
                { DicomTag.Rows, (ushort)bitmap.Height }
            };
            //var dataset = new DicomDataset();
            //dataset.Add<ushort>(DicomTag.Columns, (ushort)bitmap.Width)
            //       .Add<ushort>(DicomTag.Rows, (ushort)bitmap.Height)
            //       .Add<ushort>(DicomTag.BitsAllocated, 8)
            //       .Add<ushort>(DicomTag.BitsStored, 8)
            //       .Add<ushort>(DicomTag.HighBit, 7)
            //       .Add(DicomTag.PixelRepresentation, (ushort)PixelRepresentation.Unsigned)
            //       .Add(DicomTag.PlanarConfiguration, (ushort)PlanarConfiguration.Interleaved)
            //       .Add<ushort>(DicomTag.SamplesPerPixel, 3)
            //       .Add(DicomTag.PhotometricInterpretation, PhotometricInterpretation.Rgb.Value);

            //var pixelData = DicomPixelData.Create(dataset, true);

            var pixelData = DicomPixelData.Create(dataset, true);

            pixelData.BitsStored                = 8;
            pixelData.BitsAllocated             = 8;
            pixelData.SamplesPerPixel           = 3;
            pixelData.HighBit                   = 7;
            pixelData.PixelRepresentation       = (ushort)PixelRepresentation.Unsigned;
            pixelData.PlanarConfiguration       = (ushort)PlanarConfiguration.Interleaved;
            pixelData.PhotometricInterpretation = PhotometricInterpretation.Rgb;

            var pixels = GetColorbytes(bitmap);
            var buffer = new MemoryByteBuffer(pixels.Data);

            pixelData.AddFrame(buffer);

            var imageBox = _currentFilmBox.BasicImageBoxes[index];

            imageBox.ImageSequence = dataset;

            pixels.Dispose();
        }
Example #29
0
        /// <summary>
        /// 图片转换dcm
        /// </summary>
        /// <param name="file"></param>
        public static void Image2dcm(Img2DcmOptions options)
        {
            if (options.images.Count <= 0)
            {
                Console.WriteLine("请传入图片路径");
                return;
            }
            // 取第一张图片作为基准图片
            Bitmap bitmap = new Bitmap(@options.images[0]);

            byte[]           pixels  = GetPixels(bitmap);
            MemoryByteBuffer buffer  = new MemoryByteBuffer(pixels);
            DicomDataset     dataset = new DicomDataset();

            dataset.Add(DicomTag.SpecificCharacterSet, "GB18030");
            // 写入tag数据
            dataset.Add(DicomTag.PhotometricInterpretation, PhotometricInterpretation.Rgb.Value);
            dataset.Add(DicomTag.Rows, (ushort)bitmap.Height);
            dataset.Add(DicomTag.Columns, (ushort)bitmap.Width);
            dataset.Add(DicomTag.BitsAllocated, (ushort)8);
            dataset.Add(DicomTag.SOPClassUID, "1.2.840.10008.5.1.4.1.1.2");
            dataset.Add(DicomTag.SOPInstanceUID, "1.2.840.10008.5.1.4.1.1.2." + GetTimeStamp());
            dataset.Add(DicomTag.PatientName, Encoding.Default, string.IsNullOrEmpty(options.patientName) ? "test" : options.patientName);
            dataset.Add(DicomTag.PatientID, string.IsNullOrEmpty(options.patientID) ? Guid.NewGuid().ToString("N") : options.patientID);
            dataset.Add(DicomTag.StudyInstanceUID, "1.2.3.4.5.6.7.8.9.11." + GetTimeStamp());
            dataset.Add(DicomTag.StudyDate, DateTime.Now.ToString("yyyyMMdd"));
            dataset.Add(DicomTag.StudyTime, DateTime.Now.ToString("HHmmss"));
            dataset.Add(DicomTag.StudyID, GetTimeStamp());
            dataset.Add(DicomTag.Modality, "CT");
            dataset.Add(DicomTag.SeriesInstanceUID, "1.2.3.4.5.6.7.8.9.11." + GetTimeStamp());
            dataset.Add(DicomTag.InstanceNumber, "1000");

            DicomPixelData pixelData = DicomPixelData.Create(dataset, true);

            pixelData.BitsStored          = 8;
            pixelData.SamplesPerPixel     = 3;
            pixelData.HighBit             = 7;
            pixelData.PixelRepresentation = 0;
            pixelData.PlanarConfiguration = 0;
            pixelData.AddFrame(buffer);

            // 如果图片大于等于两张,则继续追加
            if (options.images.Count >= 2)
            {
                for (var i = 1; i < options.images.Count; i++)
                {
                    Bitmap           addBit    = new Bitmap(@options.images[i]);
                    byte[]           addPixels = GetPixels(addBit);
                    MemoryByteBuffer addBuffer = new MemoryByteBuffer(addPixels);
                    pixelData.AddFrame(addBuffer);
                }
            }

            // 保存dcm文件
            DicomFile dicomfile = new DicomFile(dataset);

            dicomfile.Save(@options.outDcm);
            Console.WriteLine("success:jpg转dcm成功");
        }
Example #30
0
        static private void ScTextGspsShapesTest(string studyDirectoryPath, string scFileName, string outputFileName, string seriesDescription)
        {
            string[] files = Directory.GetFiles(studyDirectoryPath);

            string sourceFilePath = files.Single(a => DicomFile.Open(a).Dataset.GetSingleValue <string>(DicomTag.Modality) != "PR");

            var dataset    = DicomFile.Open(sourceFilePath).Dataset;
            var image      = dataset.ReadL16Image();
            var newDataset = new DicomDataset();

            dataset.CopyTo(newDataset);

            FontCollection fontCollection = new FontCollection();
            ushort         windowCenter   = dataset.GetValue <ushort>(DicomTag.WindowCenter, 0);
            ushort         windowWidth    = dataset.GetValue <ushort>(DicomTag.WindowWidth, 0);
            ushort         colorValue     = (ushort)(windowCenter + windowWidth);
            Color          color          = new Color(new Rgba64(colorValue, colorValue, colorValue, colorValue));
            FontFamily     fontFamily     = fontCollection.Install("/media/nikolaev_ov/CEFE3C54FE3C36D5/fonts/TimesNewRoman/TimesNewRomanRegular/TimesNewRomanRegular.ttf");
            Font           font           = new Font(fontFamily, 36, FontStyle.Regular);
            var            objectCoord    = (1000F, 1000F);
            var            objectSize     = (400F, 200f);

            image.Mutate(a =>
            {
                a.DrawText("1: (Информация о находке)", font, color, new PointF(100, 100));
                a.DrawText(new DrawingOptions()
                {
                    GraphicsOptions = new GraphicsOptions(), TextOptions = new TextOptions()
                    {
                        HorizontalAlignment = HorizontalAlignment.Center
                    }
                }, "1", font, color, new PointF(objectCoord.Item1 + objectSize.Item1 * 0.5F, objectCoord.Item2 + objectSize.Item2 + 5));
            });

            var pixelData = image.ToPixelData();

            var dicomPixelData = DicomPixelData.Create(newDataset, true);

            dicomPixelData.AddFrame(new MemoryByteBuffer(pixelData));
            dataset = newDataset.Compress(DicomTransferSyntax.JPEGLSLossless, new DicomJpegLsLosslessCodec(), new DicomJpegParams());

            string destFilePath = Path.Combine(studyDirectoryPath, Path.GetFileNameWithoutExtension(scFileName) + ".dcm");

            EnsureDirectories(Path.GetDirectoryName(destFilePath));
            new DicomFile(dataset).Save(destFilePath);

            var         pre       = CreatePresentationState(new[] { sourceFilePath }, true, seriesDescription, 1);
            const float thickness = 2F;

            ColorMine.ColorSpaces.Rgb rgb = new ColorMine.ColorSpaces.Rgb {
                G = 255
            };
            AddPolyline(pre, objectCoord.Item1 + thickness * 0.5F, objectCoord.Item2 + thickness * 0.5F, objectSize.Item1 - thickness, objectSize.Item2 - thickness, thickness, rgb);

            destFilePath = Path.Combine(studyDirectoryPath, Path.GetFileNameWithoutExtension(outputFileName) + ".dcm");
            EnsureDirectories(Path.GetDirectoryName(destFilePath));
            new DicomFile(pre.PresentationStateDataset).Save(destFilePath);
        }