Exemplo n.º 1
0
        public void ChangeSyntax(TransferSyntax syntax)
        {
            try
            {
                if (!_dicomFile.TransferSyntax.Encapsulated)
                {
                    // Check if Overlay is embedded in pixels
                    OverlayPlaneModuleIod overlayIod = new OverlayPlaneModuleIod(_dicomFile.DataSet);
                    for (int i = 0; i < 16; i++)
                    {
                        if (overlayIod.HasOverlayPlane(i))
                        {
                            OverlayPlane overlay = overlayIod[i];
                            if (overlay.OverlayData == null)
                            {
                                DicomUncompressedPixelData pd = new DicomUncompressedPixelData(_dicomFile);
                                overlay.ConvertEmbeddedOverlay(pd);
                            }
                        }
                    }
                }
                else if (syntax.Encapsulated)
                {
                    // Must decompress first.
                    _dicomFile.ChangeTransferSyntax(TransferSyntax.ExplicitVrLittleEndian);
                }

                _dicomFile.ChangeTransferSyntax(syntax);
            }
            catch (Exception e)
            {
                Platform.Log(LogLevel.Error, e, "Unexpected exception compressing/decompressing DICOM file");
            }
        }
Exemplo n.º 2
0
        public static void LosslessImageTest(TransferSyntax syntax, DicomFile theFile)
        {
            if (File.Exists(theFile.Filename))
            {
                File.Delete(theFile.Filename);
            }

            DicomFile saveCopy = new DicomFile(theFile.Filename, theFile.MetaInfo.Copy(), theFile.DataSet.Copy());

            theFile.ChangeTransferSyntax(syntax);

            theFile.Save(DicomWriteOptions.ExplicitLengthSequence);

            DicomFile newFile = new DicomFile(theFile.Filename);

            newFile.Load(DicomReadOptions.Default);

            newFile.ChangeTransferSyntax(saveCopy.TransferSyntax);

            List <DicomAttributeComparisonResult> list = new List <DicomAttributeComparisonResult>();
            bool result = newFile.DataSet.Equals(saveCopy.DataSet, ref list);

            StringBuilder sb = new StringBuilder();

            foreach (DicomAttributeComparisonResult compareResult in list)
            {
                sb.AppendFormat("Comparison Failure: {0}, ", compareResult.Details);
            }

            Assert.IsTrue(result, sb.ToString());
        }
Exemplo n.º 3
0
		public static void LosslessImageTest(TransferSyntax syntax, DicomFile theFile)
		{
			if (File.Exists(theFile.Filename))
				File.Delete(theFile.Filename);

			DicomFile saveCopy = new DicomFile(theFile.Filename, theFile.MetaInfo.Copy(), theFile.DataSet.Copy());

			theFile.ChangeTransferSyntax(syntax);

			theFile.Save(DicomWriteOptions.ExplicitLengthSequence);

			DicomFile newFile = new DicomFile(theFile.Filename);

			newFile.Load(DicomReadOptions.Default);

			newFile.ChangeTransferSyntax(saveCopy.TransferSyntax);

			List<DicomAttributeComparisonResult> list = new List<DicomAttributeComparisonResult>();
			bool result = newFile.DataSet.Equals(saveCopy.DataSet, ref list);

			StringBuilder sb = new StringBuilder();
			foreach (DicomAttributeComparisonResult compareResult in list)
				sb.AppendFormat("Comparison Failure: {0}, ", compareResult.Details);

			Assert.IsTrue(result,sb.ToString());
		}
        private static void TestRoundtripFile <T>(string message, params object[] args)
            where T : IDicomCodec, new()
        {
            var filenameReference  = string.Format("reference_{0}.dcm", typeof(T).Name);
            var filenameCompressed = string.Format("compressed_{0}.dcm", typeof(T).Name);
            var codec = new T();

            // create an image
            var original = DicomImageTestHelper.CreateDicomImage();

            original.Save(filenameReference);

            // compress the image
            var compressed = new DicomFile();

            compressed.Load(DicomReadOptions.Default | DicomReadOptions.StorePixelDataReferences, filenameReference);
            compressed.ChangeTransferSyntax(codec.CodecTransferSyntax, codec, null);
            compressed.Save(filenameCompressed);

            // decompress the image
            var decompressed = new DicomFile();

            decompressed.Load(DicomReadOptions.Default | DicomReadOptions.StorePixelDataReferences, filenameCompressed);
            decompressed.ChangeTransferSyntax(TransferSyntax.ExplicitVrLittleEndian, codec, null);

            // compare results
            AssertEquals(original, decompressed, message, args);
        }
Exemplo n.º 5
0
        public void RleTest(DicomFile file)
        {
            // Make a copy of the source format
            DicomAttributeCollection originalDataSet  = file.DataSet.Copy();
            DicomAttributeCollection originalMetaInfo = file.MetaInfo.Copy();
            DicomFile originalFile = new DicomFile("", originalMetaInfo, originalDataSet);

            file.ChangeTransferSyntax(TransferSyntax.RleLossless);

            file.Save();

            DicomFile newFile = new DicomFile(file.Filename);

            newFile.Load();

            newFile.ChangeTransferSyntax(TransferSyntax.ExplicitVrLittleEndian);

            newFile.Filename = "Output" + file.Filename;
            newFile.Save();

            List <DicomAttributeComparisonResult> results = new List <DicomAttributeComparisonResult>();
            bool compare = originalFile.DataSet.Equals(newFile.DataSet, ref results);

            Assert.IsTrue(compare, results.Count > 0 ? CollectionUtils.FirstElement(results).Details : string.Empty);
        }
        private void ChangeToSyntax(TransferSyntax syntax)
        {
            string[] files = BuildFileList();
            var      args  = new SelectFolderDialogCreationArgs
            {
                Path = GetDirectoryOfFirstPath(),
                AllowCreateNewFolder = true,
                Prompt = "Select output folder"
            };

            var result = base.Context.DesktopWindow.ShowSelectFolderDialogBox(args);

            if (result.Action != DialogBoxAction.Ok)
            {
                return;
            }

            foreach (string file in files)
            {
                try
                {
                    DicomFile dicomFile = new DicomFile(file);
                    dicomFile.Load();
                    dicomFile.ChangeTransferSyntax(syntax);
                    string sourceFileName = System.IO.Path.GetFileNameWithoutExtension(file);
                    string fileName       = System.IO.Path.Combine(result.FileName, sourceFileName);
                    fileName += ".compressed.dcm";
                    dicomFile.Save(fileName);
                }
                catch (Exception e)
                {
                    ExceptionHandler.Report(e, Context.DesktopWindow);
                }
            }
        }
Exemplo n.º 7
0
        private void buttonCompress_Click(object sender, EventArgs e)
        {
            TransferSyntax syntax = this.comboBoxCompressionType.SelectedItem as TransferSyntax;

            if (syntax == null)
            {
                MessageBox.Show("Transfer syntax not selected");
                return;
            }

            DicomFile dicomFile = new DicomFile(textBoxSourceFile.Text);

            dicomFile.Load();
            if (dicomFile.TransferSyntax.Encapsulated)
            {
                MessageBox.Show(String.Format("Message encoded as {0}, cannot compress.", dicomFile.TransferSyntax));
                return;
            }

            dicomFile.Filename = textBoxDestinationFile.Text;

            dicomFile.ChangeTransferSyntax(syntax);

            dicomFile.Save();
        }
Exemplo n.º 8
0
        public void PartialFrameTest()
        {
            DicomFile file = new DicomFile("RlePartialFrameTest.dcm");

            SetupMultiframeXA(file.DataSet, 511, 511, 7);

            file.ChangeTransferSyntax(TransferSyntax.RleLossless);

            file.Save();

            DicomFile newFile = new DicomFile(file.Filename);

            newFile.Load(DicomReadOptions.StorePixelDataReferences);

            DicomPixelData pd;

            if (!newFile.TransferSyntax.Encapsulated)
            {
                pd = new DicomUncompressedPixelData(newFile);
            }
            else if (newFile.TransferSyntax.Equals(TransferSyntax.RleLossless))
            {
                pd = new DicomCompressedPixelData(newFile);
            }
            else
            {
                throw new DicomCodecException("Unsupported transfer syntax: " + newFile.TransferSyntax);
            }

            for (int i = 0; i < pd.NumberOfFrames; i++)
            {
                pd.GetFrame(i);
            }
        }
        public static void LosslessImageTestWithConversion(TransferSyntax syntax, DicomFile theFile)
        {
            if (File.Exists(theFile.Filename))
            {
                File.Delete(theFile.Filename);
            }

            DicomFile saveCopy = new DicomFile(theFile.Filename, theFile.MetaInfo.Copy(), theFile.DataSet.Copy());

            theFile.ChangeTransferSyntax(syntax);

            theFile.Save(DicomWriteOptions.ExplicitLengthSequence);

            DicomFile newFile = new DicomFile(theFile.Filename);

            newFile.Load(DicomReadOptions.Default);

            newFile.ChangeTransferSyntax(saveCopy.TransferSyntax);

            string failureDescription;
            bool   result = Compare(DicomPixelData.CreateFrom(newFile),
                                    DicomPixelData.CreateFrom(saveCopy), out failureDescription);

            Assert.IsTrue(result, failureDescription);

            Assert.IsFalse(newFile.DataSet.Equals(saveCopy.DataSet));
        }
        public static void LossyImageTest(TransferSyntax syntax, DicomFile theFile)
        {
            if (File.Exists(theFile.Filename))
            {
                File.Delete(theFile.Filename);
            }

            DicomFile saveCopy = new DicomFile(theFile.Filename, theFile.MetaInfo.Copy(), theFile.DataSet.Copy());

            theFile.ChangeTransferSyntax(syntax);

            theFile.Save(DicomWriteOptions.ExplicitLengthSequence);

            DicomFile newFile = new DicomFile(theFile.Filename);

            newFile.Load(DicomReadOptions.Default);

            newFile.ChangeTransferSyntax(saveCopy.TransferSyntax);

            Assert.IsFalse(newFile.DataSet.Equals(saveCopy.DataSet));

            Assert.IsTrue(newFile.DataSet.Contains(DicomTags.DerivationDescription));
            Assert.IsTrue(newFile.DataSet.Contains(DicomTags.LossyImageCompression));
            Assert.IsTrue(newFile.DataSet.Contains(DicomTags.LossyImageCompressionMethod));
            Assert.IsTrue(newFile.DataSet.Contains(DicomTags.LossyImageCompressionRatio));

            Assert.IsFalse(newFile.DataSet[DicomTags.DerivationDescription].IsEmpty);
            Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompression].IsEmpty);
            Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompressionMethod].IsEmpty);
            Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompressionRatio].IsEmpty);

            Assert.IsFalse(newFile.DataSet[DicomTags.DerivationDescription].IsNull);
            Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompression].IsNull);
            Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompressionMethod].IsNull);
            Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompressionRatio].IsNull);

            // Make copies of datasets, delete the tags that don't match, and ensure the same
            DicomAttributeCollection newDataSet = newFile.DataSet.Copy(true, true, true);
            DicomAttributeCollection oldDataSet = theFile.DataSet.Copy(true, true, true);

            oldDataSet.RemoveAttribute(DicomTags.PixelData);
            newDataSet.RemoveAttribute(DicomTags.PixelData);
            oldDataSet.RemoveAttribute(DicomTags.DerivationDescription);
            newDataSet.RemoveAttribute(DicomTags.DerivationDescription);
            oldDataSet.RemoveAttribute(DicomTags.LossyImageCompression);
            newDataSet.RemoveAttribute(DicomTags.LossyImageCompression);
            oldDataSet.RemoveAttribute(DicomTags.LossyImageCompressionMethod);
            newDataSet.RemoveAttribute(DicomTags.LossyImageCompressionMethod);
            oldDataSet.RemoveAttribute(DicomTags.LossyImageCompressionRatio);
            newDataSet.RemoveAttribute(DicomTags.LossyImageCompressionRatio);
            oldDataSet.RemoveAttribute(DicomTags.PhotometricInterpretation);
            newDataSet.RemoveAttribute(DicomTags.PhotometricInterpretation);

            List <DicomAttributeComparisonResult> results = new List <DicomAttributeComparisonResult>();

            bool check = oldDataSet.Equals(newDataSet, ref results);

            Assert.IsTrue(check, results.Count > 0 ? CollectionUtils.FirstElement(results).Details : string.Empty);
        }
Exemplo n.º 11
0
        /// <summary>
        /// returns dicomFile in the content type given by finalContentType in a HttpResponseMessage.
        /// If content type is dicom, transfer syntax must be set to the given transferSyntax parameter.
        /// </summary>
        /// <param name="dicomFile"></param>
        /// <param name="finalContentType"></param>
        /// <param name="transferSyntax"></param>
        /// <returns></returns>
        private HttpResponseMessage ReturnImageAsHttpResponse(DicomFile dicomFile, string finalContentType, string transferSyntax)
        {
            MediaTypeHeaderValue header = null;
            Stream streamContent        = null;

            if (finalContentType == JpegImageContentType)
            {
                DicomImage image = new DicomImage(dicomFile.Dataset);
                Bitmap     bmp   = image.RenderImage(0).As <Bitmap>();

                //When an image/jpeg MIME type is returned, the image shall be encoded using the JPEG baseline lossy 8
                //bit Huffman encoded non-hierarchical non-sequential process ISO/IEC 10918.
                //TODO Is it the case with default Jpeg format from Bitmap?
                header        = new MediaTypeHeaderValue(JpegImageContentType);
                streamContent = new MemoryStream();
                bmp.Save(streamContent, ImageFormat.Jpeg);
                streamContent.Seek(0, SeekOrigin.Begin);
            }
            else if (finalContentType == AppDicomContentType)
            {
                //By default, the transfer syntax shall be
                //"Explicit VR Little Endian".
                //Note: This implies that retrieved images are sent un-compressed by default.
                DicomTransferSyntax requestedTransferSyntax = DicomTransferSyntax.ExplicitVRLittleEndian;

                if (transferSyntax != null)
                {
                    requestedTransferSyntax = GetTransferSyntaxFromString(transferSyntax);
                }

                bool transferSyntaxIsTheSameAsSourceFile =
                    dicomFile.FileMetaInfo.TransferSyntax == requestedTransferSyntax;

                //we only change transfer syntax if we need to
                DicomFile dicomFileToStream;
                if (!transferSyntaxIsTheSameAsSourceFile)
                {
                    dicomFileToStream = dicomFile.ChangeTransferSyntax(requestedTransferSyntax);
                }
                else
                {
                    dicomFileToStream = dicomFile;
                }


                header        = new MediaTypeHeaderValue(AppDicomContentType);
                streamContent = new MemoryStream();
                dicomFileToStream.Save(streamContent);
                streamContent.Seek(0, SeekOrigin.Begin);
            }


            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);

            result.Content = new StreamContent(streamContent);
            result.Content.Headers.ContentType = header;
            return(result);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Convert the byte data retrieved from DCM file to Image
        /// </summary>
        /// <param name="imagedata"></param>
        /// <returns></returns>
        private Bitmap ConvertDCMData2BitImage(DicomFile dcm)
        {
            DicomFile newDcmFile = null;

            if (dcm.FileMetaInfo.TransferSyntax.IsEncapsulated)//if the data is compressed
            {
                // System.Reflection.Assembly.LoadFrom(Path.Combine(Application.StartupPath,"Dicom.Native64.dll"));
                DicomTranscoder.LoadCodecs(Application.StartupPath, "Dicom.Native*.dll");
                newDcmFile = dcm.ChangeTransferSyntax(DicomTransferSyntax.ExplicitVRLittleEndian, new DicomJpegLsParams());
            }
            DicomImage imageDcm = null;

            if (newDcmFile != null)
            {
                imageDcm = new DicomImage(newDcmFile.Dataset);
            }
            else
            {
                imageDcm = new DicomImage(dcm.Dataset);
            }
            DicomDataset dataset = dcm.Dataset;

            byte[] fs      = imageDcm.PixelData.NumberOfFrames < 2 ? imageDcm.PixelData.GetFrame(0).Data : imageDcm.PixelData.GetFrame(1).Data;
            uint   size    = (uint)Marshal.SizeOf(typeof(short));
            uint   padding = (uint)fs.Length % size;
            uint   count   = (uint)fs.Length / size;

            short[] values = new short[count];
            System.Buffer.BlockCopy(fs, 0, values, 0, (int)(fs.Length - padding));

            int height        = dataset.Get <int>(DicomTag.Rows);
            int width         = dataset.Get <int>(DicomTag.Columns);
            int windowsWidth  = (int)dataset.Get <double>(DicomTag.WindowWidth);
            int windowsCenter = (int)dataset.Get <double>(DicomTag.WindowCenter);

            //if the windowsWidth = 0, the DCM file is not standard type.
            if (windowsWidth == 0 || windowsCenter == 0)
            {
                windowsWidth  = values.Max <short>() - values.Min <short>();
                windowsCenter = windowsWidth / 2;
            }
            int    low    = windowsCenter - windowsWidth / 2;
            int    high   = windowsCenter + windowsWidth / 2;
            Bitmap bitmap = new Bitmap(width, height);

            for (int i = 0; i < height; ++i)
            {
                for (int j = 0; j < width; ++j)
                {
                    int r, g, b;
                    int temp = (int)values[(width - j - 1) * height + i];
                    int val  = temp > high ? 255 : (temp < low ? 0 : ((temp - low) * 255 / windowsWidth));
                    r = g = b = val;
                    bitmap.SetPixel(i, width - j - 1, Color.FromArgb(r, g, b));
                }
            }
            return(bitmap);
        }
Exemplo n.º 13
0
 public void ChangeSyntax(TransferSyntax syntax)
 {
     try
     {
         _dicomFile.ChangeTransferSyntax(syntax);
     }
     catch (Exception e)
     {
         Logger.LogErrorException(e, "Unexpected exception compressing/decompressing DICOM file");
     }
 }
Exemplo n.º 14
0
 public bool ChangeTransferSyntax(DicomTransferSyntax newTransferSyntax)
 {
     try
     {
         DicomFile = DicomFile.ChangeTransferSyntax(newTransferSyntax);
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
        public static void ExpectedFailureTest(TransferSyntax syntax, DicomFile theFile)
        {
            try
            {
                theFile.ChangeTransferSyntax(syntax);
            }
            catch (DicomCodecUnsupportedSopException)
            {
                return;
            }

            Assert.IsTrue(false, "Unexpected successful compression of object.");
        }
        private void ChangeToSyntax(IBackgroundTaskContext context)
        {
            var study = (StudyTableItem)context.UserState;

            try
            {
                _tempPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "ClearCanvas");
                _tempPath = System.IO.Path.Combine(_tempPath, "Compression");
                _tempPath = System.IO.Path.Combine(_tempPath, Path.GetRandomFileName());

                string message = String.Format("Changing transfer syntax to: {0}", _syntax);
                context.ReportProgress(new BackgroundTaskProgress(0, message));
                var loader       = study.Server.GetService <IStudyLoader>();
                int numberOfSops = loader.Start(new StudyLoaderArgs(study.StudyInstanceUid, null));
                if (numberOfSops <= 0)
                {
                    return;
                }

                for (int i = 0; i < numberOfSops; ++i)
                {
                    Sop sop = loader.LoadNextSop();
                    if (sop != null)
                    {
                        if (sop.DataSource is ILocalSopDataSource)
                        {
                            string    filename = Path.Combine(_tempPath, string.Format("{0}.dcm", i));
                            DicomFile file     = ((ILocalSopDataSource)sop.DataSource).File;
                            file.ChangeTransferSyntax(_syntax);
                            file.Save(filename);
                        }
                    }

                    int progressPercent = (int)Math.Floor((i + 1) / (float)numberOfSops * 100);
                    context.ReportProgress(new BackgroundTaskProgress(progressPercent, message));
                }

                //trigger an import of the anonymized files.
                var client = new DicomFileImportBridge();
                client.ImportFileList(new List <string> {
                    _tempPath
                }, BadFileBehaviourEnum.Move, FileImportBehaviourEnum.Move);

                context.Complete();
            }
            catch (Exception e)
            {
                context.Error(e);
            }
        }
Exemplo n.º 17
0
        public void RleOverlayTest()
        {
            DicomFile file = new DicomFile("RleCodecOverlayTest.dcm");

            SetupMRWithOverlay(file.DataSet);

            SetupMetaInfo(file);

            // Save a copy
            file.Save();


            // Load the file into new DicomFile object
            DicomFile newFile = new DicomFile(file.Filename);

            newFile.Load();

            OverlayPlaneModuleIod overlayIod = new OverlayPlaneModuleIod(newFile.DataSet);
            OverlayPlane          overlay    = overlayIod[0];

            // SHould be no OverlayData tag
            Assert.IsNull(overlay.OverlayData, "Overlay should be in pixel data");

            // Overlay should be extracted out of pixel data here
            newFile.ChangeTransferSyntax(TransferSyntax.RleLossless);

            Assert.IsNotNull(overlay.OverlayData, "Overlay Data is not null");

            newFile.Save();

            // Load a new copy
            newFile = new DicomFile(file.Filename);

            newFile.Load();

            newFile.ChangeTransferSyntax(TransferSyntax.ExplicitVrLittleEndian);

            newFile.Filename = "Output" + file.Filename;
            newFile.Save();

            List <DicomAttributeComparisonResult> results = new List <DicomAttributeComparisonResult>();
            bool compare = file.DataSet.Equals(newFile.DataSet, ref results);

            // Shouldn't be the same, OverlayData tag should have been added
            Assert.IsFalse(compare, results.Count > 0 ? CollectionUtils.FirstElement(results).Details : string.Empty);
        }
Exemplo n.º 18
0
        private void SetupEncapsulatedImageWithIconSequence(DicomFile file, bool encapsulateIconPixelData)
        {
            var codec = new NullDicomCodec();

            DicomAttributeCollection dataSet = file.DataSet;

            SetupSecondaryCapture(dataSet);

            SetupMetaInfo(file);

            file.TransferSyntax = TransferSyntax.ImplicitVrLittleEndian;
            file.ChangeTransferSyntax(codec.CodecTransferSyntax);

            // explicitly create the icon sequence as either encapsulated or native, so that we are not depending on correct behaviour elsewhere...
            CreateIconImageSequence(dataSet);

            if (encapsulateIconPixelData)
            {
                var dataset   = ((DicomAttributeSQ)dataSet[DicomTags.IconImageSequence])[0];
                var pixelData = dataset[DicomTags.PixelData];

                var pd = new DicomUncompressedPixelData(dataset);
                using (var pixelStream = ((DicomAttributeBinary)pixelData).AsStream())
                {
                    //Before compression, make the pixel data more "typical", so it's harder to mess up the codecs.
                    //NOTE: Could combine mask and align into one method so we're not iterating twice, but I prefer having the methods separate.
                    if (DicomUncompressedPixelData.RightAlign(pixelStream, pd.BitsAllocated, pd.BitsStored, pd.HighBit))
                    {
                        var newHighBit = (ushort)(pd.HighBit - pd.LowBit);

                        pd.HighBit = newHighBit;                         //correct high bit after right-aligning.
                        dataset[DicomTags.HighBit].SetUInt16(0, newHighBit);
                    }
                    DicomUncompressedPixelData.ZeroUnusedBits(pixelStream, pd.BitsAllocated, pd.BitsStored, pd.HighBit);
                }

                // Set transfer syntax before compression, the codecs need it.
                var fragments = new DicomCompressedPixelData(pd)
                {
                    TransferSyntax = codec.CodecTransferSyntax
                };
                codec.Encode(pd, fragments, null);
                fragments.UpdateAttributeCollection(dataset);
            }
        }
Exemplo n.º 19
0
        private void buttonDecompress_Click(object sender, EventArgs e)
        {
            if (this.textBoxSourceFile.Text.Length == 0 || this.textBoxDestinationFile.Text.Length == 0)
            {
                MessageBox.Show("Invalid source or destination filename");
                return;
            }

            DicomFile dicomFile = new DicomFile(textBoxSourceFile.Text);

            dicomFile.Load();

            dicomFile.Filename = textBoxDestinationFile.Text;

            dicomFile.ChangeTransferSyntax(TransferSyntax.ExplicitVrLittleEndian);

            dicomFile.Save();
        }
Exemplo n.º 20
0
		private void SetupEncapsulatedImageWithIconSequence(DicomFile file, bool encapsulateIconPixelData)
		{
			var codec = new NullDicomCodec();

			DicomAttributeCollection dataSet = file.DataSet;

			SetupSecondaryCapture(dataSet);

			SetupMetaInfo(file);

			file.TransferSyntax = TransferSyntax.ImplicitVrLittleEndian;
			file.ChangeTransferSyntax(codec.CodecTransferSyntax);

			// explicitly create the icon sequence as either encapsulated or native, so that we are not depending on correct behaviour elsewhere...
			CreateIconImageSequence(dataSet);

			if (encapsulateIconPixelData)
			{
				var dataset = ((DicomAttributeSQ) dataSet[DicomTags.IconImageSequence])[0];
				var pixelData = dataset[DicomTags.PixelData];

				var pd = new DicomUncompressedPixelData(dataset);
				using (var pixelStream = ((DicomAttributeBinary) pixelData).AsStream())
				{
					//Before compression, make the pixel data more "typical", so it's harder to mess up the codecs.
					//NOTE: Could combine mask and align into one method so we're not iterating twice, but I prefer having the methods separate.
					if (DicomUncompressedPixelData.RightAlign(pixelStream, pd.BitsAllocated, pd.BitsStored, pd.HighBit))
					{
						var newHighBit = (ushort) (pd.HighBit - pd.LowBit);

						pd.HighBit = newHighBit; //correct high bit after right-aligning.
						dataset[DicomTags.HighBit].SetUInt16(0, newHighBit);
					}
					DicomUncompressedPixelData.ZeroUnusedBits(pixelStream, pd.BitsAllocated, pd.BitsStored, pd.HighBit);
				}

				// Set transfer syntax before compression, the codecs need it.
				var fragments = new DicomCompressedPixelData(pd) {TransferSyntax = codec.CodecTransferSyntax};
				codec.Encode(pd, fragments, null);
				fragments.UpdateAttributeCollection(dataset);
			}
		}
Exemplo n.º 21
0
        public static void LosslessImageTestWithConversion(TransferSyntax syntax, DicomFile theFile)
        {
            if (File.Exists(theFile.Filename))
            {
                File.Delete(theFile.Filename);
            }

            DicomFile saveCopy = new DicomFile(theFile.Filename, theFile.MetaInfo.Copy(), theFile.DataSet.Copy());

            theFile.ChangeTransferSyntax(syntax);

            theFile.Save(DicomWriteOptions.ExplicitLengthSequence);

            DicomFile newFile = new DicomFile(theFile.Filename);

            newFile.Load(DicomReadOptions.Default);

            newFile.ChangeTransferSyntax(saveCopy.TransferSyntax);

            Assert.IsFalse(newFile.DataSet.Equals(saveCopy.DataSet));
        }
Exemplo n.º 22
0
        public void RleTest(DicomFile file)
        {
            // Make a copy of the source format
            DicomAttributeCollection originalDataSet  = file.DataSet.Copy();
            DicomAttributeCollection originalMetaInfo = file.MetaInfo.Copy();
            DicomFile originalFile = new DicomFile("", originalMetaInfo, originalDataSet);

            file.ChangeTransferSyntax(TransferSyntax.RleLossless);

            file.Save();

            DicomFile newFile = new DicomFile(file.Filename);

            newFile.Load();

            newFile.ChangeTransferSyntax(TransferSyntax.ExplicitVrLittleEndian);

            newFile.Filename = "Output" + file.Filename;
            newFile.Save();

            Assert.AreEqual(originalFile.DataSet.Equals(newFile.DataSet), true);
        }
Exemplo n.º 23
0
        public static void LossyImageTest(TransferSyntax syntax, DicomFile theFile)
        {
            if (File.Exists(theFile.Filename))
            {
                File.Delete(theFile.Filename);
            }

            DicomFile saveCopy = new DicomFile(theFile.Filename, theFile.MetaInfo.Copy(), theFile.DataSet.Copy());

            theFile.ChangeTransferSyntax(syntax);

            theFile.Save(DicomWriteOptions.ExplicitLengthSequence);

            DicomFile newFile = new DicomFile(theFile.Filename);

            newFile.Load(DicomReadOptions.Default);

            newFile.ChangeTransferSyntax(saveCopy.TransferSyntax);

            Assert.IsFalse(newFile.DataSet.Equals(saveCopy.DataSet));

            Assert.IsTrue(newFile.DataSet.Contains(DicomTags.DerivationDescription));
            Assert.IsTrue(newFile.DataSet.Contains(DicomTags.LossyImageCompression));
            Assert.IsTrue(newFile.DataSet.Contains(DicomTags.LossyImageCompressionMethod));
            Assert.IsTrue(newFile.DataSet.Contains(DicomTags.LossyImageCompressionRatio));

            Assert.IsFalse(newFile.DataSet[DicomTags.DerivationDescription].IsEmpty);
            Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompression].IsEmpty);
            Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompressionMethod].IsEmpty);
            Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompressionRatio].IsEmpty);

            Assert.IsFalse(newFile.DataSet[DicomTags.DerivationDescription].IsNull);
            Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompression].IsNull);
            Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompressionMethod].IsNull);
            Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompressionRatio].IsNull);
        }
Exemplo n.º 24
0
		public static void LosslessImageTestWithConversion(TransferSyntax syntax, DicomFile theFile)
		{
			if (File.Exists(theFile.Filename))
				File.Delete(theFile.Filename);

			DicomFile saveCopy = new DicomFile(theFile.Filename, theFile.MetaInfo.Copy(), theFile.DataSet.Copy());

			theFile.ChangeTransferSyntax(syntax);

			theFile.Save(DicomWriteOptions.ExplicitLengthSequence);

			DicomFile newFile = new DicomFile(theFile.Filename);

			newFile.Load(DicomReadOptions.Default);

			newFile.ChangeTransferSyntax(saveCopy.TransferSyntax);

			Assert.IsFalse(newFile.DataSet.Equals(saveCopy.DataSet));
		}
        private ProcessDuplicateResult ProcessDuplicate(DicomFile dupFile, WorkQueueUid uid, StudyXml studyXml)
        {
            var result = new ProcessDuplicateResult();


            string duplicateSopPath = ServerPlatform.GetDuplicateUidPath(StorageLocation, uid);
            string basePath         = StorageLocation.GetSopInstancePath(uid.SeriesInstanceUid, uid.SopInstanceUid);

            if (!File.Exists(basePath))
            {
                // NOTE: This is special case. The file which caused dicom service to think this sop is a duplicate
                // no longer exists in the study folder. Perhaps it has been moved to another folder during auto reconciliation.
                // We have nothing to compare against so let's just throw it into the SIQ queue.
                CreateDuplicateSIQEntry(uid, dupFile, null);
                result.ActionTaken = DuplicateProcessResultAction.Reconcile;
            }
            else
            {
                // Check if system is configured to override the rule for this study
                if (DuplicatePolicy.IsParitionDuplicatePolicyOverridden(this.StorageLocation))
                {
                    return(OverwriteDuplicate(dupFile, uid, studyXml));
                }
                else
                {
                    var baseFile = new DicomFile(basePath);
                    baseFile.Load();

                    if (DuplicateSopProcessorHelper.SopClassIsReport(dupFile.SopClass.Uid) && ServerPartition.AcceptLatestReport)
                    {
                        return(ProcessDuplicateReport(dupFile, baseFile, uid, studyXml));
                    }


                    if (!dupFile.TransferSyntax.Equals(baseFile.TransferSyntax))
                    {
                        // If they're compressed, and we have a codec, lets decompress and still do the comparison
                        if (dupFile.TransferSyntax.Encapsulated &&
                            !dupFile.TransferSyntax.LossyCompressed &&
                            DicomCodecRegistry.GetCodec(dupFile.TransferSyntax) != null)
                        {
                            dupFile.ChangeTransferSyntax(TransferSyntax.ExplicitVrLittleEndian);
                        }

                        if (baseFile.TransferSyntax.Encapsulated &&
                            !baseFile.TransferSyntax.LossyCompressed &&
                            DicomCodecRegistry.GetCodec(baseFile.TransferSyntax) != null)
                        {
                            baseFile.ChangeTransferSyntax(TransferSyntax.ExplicitVrLittleEndian);
                        }

                        if (dupFile.TransferSyntax.Encapsulated || baseFile.TransferSyntax.Encapsulated)
                        {
                            string failure = String.Format("Base file transfer syntax is '{0}' while duplicate file has '{1}'",
                                                           baseFile.TransferSyntax, dupFile.TransferSyntax);

                            var list          = new List <DicomAttributeComparisonResult>();
                            var compareResult = new DicomAttributeComparisonResult
                            {
                                ResultType = ComparisonResultType.DifferentValues,
                                TagName    = DicomTagDictionary.GetDicomTag(DicomTags.TransferSyntaxUid).Name,
                                Details    = failure
                            };
                            list.Add(compareResult);
                            CreateDuplicateSIQEntry(uid, dupFile, list);
                            result.ActionTaken = DuplicateProcessResultAction.Reconcile;
                            return(result);
                        }
                    }

                    var failureReason = new List <DicomAttributeComparisonResult>();
                    if (baseFile.DataSet.Equals(dupFile.DataSet, ref failureReason))
                    {
                        Platform.Log(LogLevel.Info,
                                     "Duplicate SOP being processed is identical.  Removing SOP: {0}",
                                     baseFile.MediaStorageSopInstanceUid);


                        RemoveWorkQueueUid(uid, duplicateSopPath);
                        result.ActionTaken = DuplicateProcessResultAction.Delete;
                    }
                    else
                    {
                        CreateDuplicateSIQEntry(uid, dupFile, failureReason);
                        result.ActionTaken = DuplicateProcessResultAction.Reconcile;
                    }
                }
            }

            return(result);
        }
Exemplo n.º 26
0
        public static void Bmp2Dcm(string bmpPath, string dcmPath, string patient_name, string sex, string age, string process_num, string modality, string hospital_name, string study_description = "", string studydate = "", int TransferSyntax = -1, string sop_uid = "")
        {
            Bitmap bitmap = new Bitmap(bmpPath);

            bitmap = DicomUtility.GetValidImage(bitmap);
            int rows;
            int columns;

            byte[]           pixels   = DicomUtility.GetPixelsForDicom(bitmap, out rows, out columns);
            MemoryByteBuffer buffer   = new MemoryByteBuffer(pixels);
            DicomDataset     dataset  = new DicomDataset();
            Encoding         encoding = Encoding.GetEncoding("GB18030");

            dataset.Add <DicomUID>(DicomTag.SOPClassUID, new DicomUID[]
            {
                DicomUID.SecondaryCaptureImageStorage
            });
            dataset.Add <DicomUID>(DicomTag.StudyInstanceUID, new DicomUID[]
            {
                DicomUtility.GenerateUid()
            });
            dataset.Add <DicomUID>(DicomTag.SeriesInstanceUID, new DicomUID[]
            {
                DicomUtility.GenerateUid()
            });
            dataset.Add <DicomUID>(DicomTag.SOPInstanceUID, new DicomUID[]
            {
                DicomUtility.GenerateUid()
            });
            dataset.Add <string>(DicomTag.PatientID, new string[]
            {
                process_num
            });
            dataset.Add(new DicomItem[]
            {
                DicomUtility.GetDicomItem(DicomTag.PatientName, encoding, patient_name)
            });
            dataset.Add <string>(DicomTag.PatientBirthDate, new string[]
            {
                "00000000"
            });
            dataset.Add(new DicomItem[]
            {
                DicomUtility.GetDicomItem(DicomTag.PatientAge, encoding, age)
            });
            dataset.Add <string>(DicomTag.PatientSex, new string[]
            {
                sex
            });
            if (studydate == "")
            {
                dataset.Add <DateTime>(DicomTag.StudyDate, new DateTime[]
                {
                    DateTime.Now
                });
                dataset.Add <DateTime>(DicomTag.StudyTime, new DateTime[]
                {
                    DateTime.Now
                });
            }
            else
            {
                dataset.Add <string>(DicomTag.StudyDate, new string[]
                {
                    studydate
                });
                dataset.Add <string>(DicomTag.StudyTime, new string[]
                {
                    DateTime.Now.ToString("hhmmssfff")
                });
            }
            dataset.Add <string>(DicomTag.AccessionNumber, new string[]
            {
                string.Empty
            });
            dataset.Add <string>(DicomTag.ReferringPhysicianName, new string[]
            {
                string.Empty
            });
            dataset.Add <string>(DicomTag.StudyID, new string[]
            {
                "1"
            });
            dataset.Add <string>(DicomTag.SeriesNumber, new string[]
            {
                "1"
            });
            dataset.Add <string>(DicomTag.ModalitiesInStudy, new string[]
            {
                modality
            });
            dataset.Add <string>(DicomTag.Modality, new string[]
            {
                modality
            });
            dataset.Add <string>(DicomTag.NumberOfStudyRelatedInstances, new string[]
            {
                "1"
            });
            dataset.Add <string>(DicomTag.NumberOfStudyRelatedSeries, new string[]
            {
                "1"
            });
            dataset.Add <string>(DicomTag.NumberOfSeriesRelatedInstances, new string[]
            {
                "1"
            });
            dataset.Add <string>(DicomTag.PatientOrientation, new string[]
            {
                "F/A"
            });
            dataset.Add <string>(DicomTag.ImageLaterality, new string[]
            {
                "U"
            });
            dataset.Add(new DicomItem[]
            {
                DicomUtility.GetDicomItem(DicomTag.InstitutionName, encoding, hospital_name)
            });
            dataset.Add <string>(DicomTag.StudyDescription, new string[]
            {
                study_description
            });
            dataset.Add <string>(DicomTag.PhotometricInterpretation, new string[]
            {
                PhotometricInterpretation.Rgb.Value
            });
            dataset.Add <ushort>(DicomTag.Rows, new ushort[]
            {
                (ushort)rows
            });
            dataset.Add <ushort>(DicomTag.Columns, new ushort[]
            {
                (ushort)columns
            });
            if (sop_uid != "")
            {
                dataset.Add <string>(DicomTag.SOPInstanceUID, new string[]
                {
                    sop_uid
                });
            }
            DicomPixelData pixelData = DicomPixelData.Create(dataset, true);

            pixelData.BitsStored          = 8;
            pixelData.BitsAllocated       = 8;
            pixelData.SamplesPerPixel     = 3;
            pixelData.HighBit             = 7;
            pixelData.PixelRepresentation = PixelRepresentation.Unsigned;
            pixelData.PlanarConfiguration = PlanarConfiguration.Interleaved;
            pixelData.AddFrame(buffer);
            DicomFile _dicomfile = new DicomFile(dataset);
            DicomFile file       = new DicomFile();

            switch (TransferSyntax)
            {
            case 0:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.JPEG2000Lossless, null);
                goto IL_579;

            case 1:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.RLELossless, null);
                goto IL_579;

            case 2:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.JPEGProcess14, null);
                goto IL_579;

            case 3:
            {
                int bits = _dicomfile.Dataset.Get <int>(DicomTag.BitsAllocated, 0, 8);
                DicomTransferSyntax syntax = DicomTransferSyntax.JPEGProcess1;
                if (bits == 16)
                {
                    syntax = DicomTransferSyntax.JPEGProcess2_4;
                }
                file = _dicomfile.ChangeTransferSyntax(syntax, new DicomJpegParams
                    {
                        Quality = 100
                    });
                goto IL_579;
            }

            case 4:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.ExplicitVRLittleEndian, null);
                goto IL_579;

            case 5:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.ExplicitVRBigEndian, null);
                goto IL_579;

            case 6:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.ImplicitVRLittleEndian, null);
                goto IL_579;

            case 8:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.ImplicitVRBigEndian, null);
                goto IL_579;
            }
            file = _dicomfile;
IL_579:
            file.Save(dcmPath);
        }
Exemplo n.º 27
0
        /// <summary>
        /// 将BMP文件转换成DICOM文件
        /// </summary>
        /// <param name="file"></param>
        public static void Bmp2Dcm(string bmpPath, string dcmPath, int TransferSyntax = -1, string sop_uid = "")
        {
            Bitmap bitmap = new Bitmap(bmpPath);

            bitmap = GetValidImage(bitmap);
            int rows, columns;

            byte[]           pixels  = GetPixelsForDicom(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);
            if (sop_uid != "")
            {
                dataset.Add(DicomTag.SOPInstanceUID, sop_uid);
            }
            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 file       = new DicomFile();

            switch (TransferSyntax)
            {
            case 0:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.JPEG2000Lossless);
                break;

            case 1:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.RLELossless);
                break;

            case 2:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.JPEGProcess14);
                break;

            //JPEG Lossy P1 && P4
            case 3:
                var bits   = _dicomfile.Dataset.Get <int>(DicomTag.BitsAllocated, 0, 8);
                var syntax = DicomTransferSyntax.JPEGProcess1;
                if (bits == 16)
                {
                    syntax = DicomTransferSyntax.JPEGProcess2_4;
                }
                file = _dicomfile.ChangeTransferSyntax(syntax, new DicomJpegParams
                {
                    Quality = 100
                });
                break;

            case 4:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.ExplicitVRLittleEndian);
                break;

            case 5:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.ExplicitVRBigEndian);
                break;

            case 6:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.ImplicitVRLittleEndian);
                break;

            case 8:
                file = _dicomfile.ChangeTransferSyntax(DicomTransferSyntax.ImplicitVRBigEndian);
                break;

            default:
                file = _dicomfile;
                break;
            }


            file.Save(dcmPath);
        }
Exemplo n.º 28
0
		public static void LosslessImageTestWithConversion(TransferSyntax syntax, DicomFile theFile)
		{
			if (File.Exists(theFile.Filename))
				File.Delete(theFile.Filename);

			DicomFile saveCopy = new DicomFile(theFile.Filename, theFile.MetaInfo.Copy(), theFile.DataSet.Copy());

			theFile.ChangeTransferSyntax(syntax);

			theFile.Save(DicomWriteOptions.ExplicitLengthSequence);

			DicomFile newFile = new DicomFile(theFile.Filename);

			newFile.Load(DicomReadOptions.Default);

			newFile.ChangeTransferSyntax(saveCopy.TransferSyntax);

            string failureDescription;
            bool result = Compare(DicomPixelData.CreateFrom(newFile),
                                  DicomPixelData.CreateFrom(saveCopy), out failureDescription);
            Assert.IsTrue(result, failureDescription);

			Assert.IsFalse(newFile.DataSet.Equals(saveCopy.DataSet));
		}
Exemplo n.º 29
0
        public void RleTest(DicomFile file)
        {
            // Make a copy of the source format
        	DicomAttributeCollection originalDataSet = file.DataSet.Copy();
            DicomAttributeCollection originalMetaInfo = file.MetaInfo.Copy();
            DicomFile originalFile = new DicomFile("", originalMetaInfo, originalDataSet);

            file.ChangeTransferSyntax(TransferSyntax.RleLossless);

            file.Save();

            DicomFile newFile = new DicomFile(file.Filename);

            newFile.Load();

            newFile.ChangeTransferSyntax(TransferSyntax.ExplicitVrLittleEndian);

            newFile.Filename = "Output" + file.Filename;
            newFile.Save();

            Assert.AreEqual(originalFile.DataSet.Equals(newFile.DataSet), true);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Compares received duplicate with the existing copy in the filesystem and throw it into the SIQ if they differ.
        /// Otherwise, simply delete the duplicate and keep everything as it.
        /// </summary>
        /// <param name="dupFile"></param>
        /// <param name="baseFile"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        private ProcessDuplicateResult CompareDuplicates(DicomFile dupFile, DicomFile baseFile, WorkQueueUid uid)
        {
            var    result           = new ProcessDuplicateResult();
            string duplicateSopPath = ServerHelper.GetDuplicateUidPath(StorageLocation, uid);

            if (!dupFile.TransferSyntax.Equals(baseFile.TransferSyntax))
            {
                // If they're compressed, and we have a codec, lets decompress and still do the comparison
                if (dupFile.TransferSyntax.Encapsulated &&
                    !dupFile.TransferSyntax.LossyCompressed &&
                    DicomCodecRegistry.GetCodec(dupFile.TransferSyntax) != null)
                {
                    dupFile.ChangeTransferSyntax(TransferSyntax.ExplicitVrLittleEndian);
                }

                if (baseFile.TransferSyntax.Encapsulated &&
                    !baseFile.TransferSyntax.LossyCompressed &&
                    DicomCodecRegistry.GetCodec(baseFile.TransferSyntax) != null)
                {
                    baseFile.ChangeTransferSyntax(TransferSyntax.ExplicitVrLittleEndian);
                }

                if (dupFile.TransferSyntax.Encapsulated || baseFile.TransferSyntax.Encapsulated)
                {
                    string failure = String.Format("Base file transfer syntax is '{0}' while duplicate file has '{1}'",
                                                   baseFile.TransferSyntax, dupFile.TransferSyntax);

                    var list          = new List <DicomAttributeComparisonResult>();
                    var compareResult = new DicomAttributeComparisonResult
                    {
                        ResultType = ComparisonResultType.DifferentValues,
                        TagName    = DicomTagDictionary.GetDicomTag(DicomTags.TransferSyntaxUid).Name,
                        Details    = failure
                    };
                    list.Add(compareResult);
                    CreateDuplicateSIQEntry(uid, dupFile, list);
                    result.ActionTaken = DuplicateProcessResultAction.Reconcile;
                    return(result);
                }
            }

            var failureReason = new List <DicomAttributeComparisonResult>();

            if (baseFile.DataSet.Equals(dupFile.DataSet, ref failureReason))
            {
                Platform.Log(LogLevel.Info,
                             "Duplicate SOP being processed is identical.  Removing SOP: {0}",
                             baseFile.MediaStorageSopInstanceUid);


                RemoveWorkQueueUid(uid, duplicateSopPath);
                result.ActionTaken = DuplicateProcessResultAction.Delete;
            }
            else
            {
                CreateDuplicateSIQEntry(uid, dupFile, failureReason);
                result.ActionTaken = DuplicateProcessResultAction.Reconcile;
            }

            return(result);
        }
Exemplo n.º 31
0
        public void RleOverlayTest()
        {
            DicomFile file = new DicomFile("RleCodecOverlayTest.dcm");

            SetupMRWithOverlay(file.DataSet);

            SetupMetaInfo(file);

            // Save a copy
            file.Save();


            // Load the file into new DicomFile object
            DicomFile newFile = new DicomFile(file.Filename);

            newFile.Load();

            OverlayPlaneModuleIod overlayIod = new OverlayPlaneModuleIod(newFile.DataSet);
            OverlayPlane overlay = overlayIod[0];
            
            // SHould be no OverlayData tag
            Assert.IsNull(overlay.OverlayData, "Overlay should be in pixel data");

            // Overlay should be extracted out of pixel data here
            newFile.ChangeTransferSyntax(TransferSyntax.RleLossless);

            Assert.IsNotNull(overlay.OverlayData,"Overlay Data is not null");

            newFile.Save();

            // Load a new copy
            newFile = new DicomFile(file.Filename);

            newFile.Load();

            newFile.ChangeTransferSyntax(TransferSyntax.ExplicitVrLittleEndian);

            newFile.Filename = "Output" + file.Filename;
            newFile.Save();

            List<DicomAttributeComparisonResult> results = new List<DicomAttributeComparisonResult>();
            bool compare = file.DataSet.Equals(newFile.DataSet, ref results);

            // Shouldn't be the same, OverlayData tag should have been added
            Assert.IsFalse(compare, results.Count > 0 ? CollectionUtils.FirstElement(results).Details : string.Empty);                      
        }
        public void ChangeAspectRatio(DicomFile file)
        {
            if (NewAspectRatio.IsNull || FloatComparer.AreEqual(NewAspectRatio.Value, 1))
            {
                throw new InvalidOperationException("Invalid new aspect ratio");
            }

            if (file.TransferSyntax.Encapsulated)
            {
                file.ChangeTransferSyntax(TransferSyntax.ExplicitVrLittleEndian);
            }

            OldInfo = new PixelDataInfo(file.DataSet);
            if (!OldInfo.IsSquare)
            {
                throw new ArgumentException("Pixels are already non-square.");
            }

            NewInfo             = OldInfo.Clone();
            NewInfo.AspectRatio = NewAspectRatio;

            if (IncreasePixelDimensions)
            {
                if (NewAspectRatio.Value < 1)
                {
                    NewInfo.Rows = (int)(OldInfo.Rows / NewAspectRatio.Value + 0.5);
                }
                else
                {
                    NewInfo.Columns = (int)(OldInfo.Columns * NewAspectRatio.Value + 0.5);
                }
            }
            else
            {
                if (NewAspectRatio.Value < 1)
                {
                    NewInfo.Columns = (int)(OldInfo.Columns * NewAspectRatio.Value + 0.5);
                }
                else
                {
                    NewInfo.Rows = (int)(OldInfo.Rows / NewAspectRatio.Value + 0.5);
                }
            }

            float rowScale = OldInfo.Rows / (float)NewInfo.Rows;
            float colScale = OldInfo.Columns / (float)NewInfo.Columns;

            if (RemoveCalibration)
            {
                NewInfo.PixelSpacing       = new PixelSpacing(0, 0);
                NewInfo.ImagerPixelSpacing = new PixelSpacing(0, 0);
            }
            else
            {
                NewInfo.PixelSpacing       = new PixelSpacing(NewInfo.PixelSpacing.Row * rowScale, NewInfo.PixelSpacing.Column * colScale);
                NewInfo.ImagerPixelSpacing = new PixelSpacing(NewInfo.ImagerPixelSpacing.Row * rowScale, NewInfo.ImagerPixelSpacing.Column * colScale);
            }

            ValidateNewInfo();

            NewInfo.SeriesDescription = (OldInfo.SeriesDescription ?? "") + String.Format(" ({0}:{1}, dim/cal={2}/{3})",
                                                                                          NewAspectRatio.Row, NewAspectRatio.Column,
                                                                                          IncreasePixelDimensions ? "y" : "n",
                                                                                          NewInfo.IsCalibrated ? "y" : "n");

            NewInfo.PlanarConfiguration = 0;

            PixelData oldPixelData = OldInfo.GetPixelData();
            PixelData newPixelData = NewInfo.GetPixelData();

            for (int row = 0; row < NewInfo.Rows; ++row)
            {
                for (int column = 0; column < NewInfo.Columns; ++column)
                {
                    var sourcePoint  = new PointF(column * colScale, row * rowScale);
                    int interpolated = PerformBilinearInterpolationAt(oldPixelData, sourcePoint);
                    newPixelData.SetPixel(column, row, interpolated);
                }
            }

            NewInfo.SetPixelData(newPixelData);
            NewInfo.UpdateDataSet(file.DataSet);
        }
Exemplo n.º 33
0
        public void RleTest(DicomFile file)
        {
            // Make a copy of the source format
        	DicomAttributeCollection originalDataSet = file.DataSet.Copy();
            DicomAttributeCollection originalMetaInfo = file.MetaInfo.Copy();
            DicomFile originalFile = new DicomFile("", originalMetaInfo, originalDataSet);

            file.ChangeTransferSyntax(TransferSyntax.RleLossless);

            file.Save();

            DicomFile newFile = new DicomFile(file.Filename);

            newFile.Load();

            newFile.ChangeTransferSyntax(TransferSyntax.ExplicitVrLittleEndian);

            newFile.Filename = "Output" + file.Filename;
            newFile.Save();

            List<DicomAttributeComparisonResult> results = new List<DicomAttributeComparisonResult>();
            bool compare = originalFile.DataSet.Equals(newFile.DataSet, ref results);
            Assert.IsTrue(compare, results.Count > 0 ? CollectionUtils.FirstElement(results).Details : string.Empty);
        }
Exemplo n.º 34
0
		public static void LossyImageTest(TransferSyntax syntax, DicomFile theFile)
		{
			if (File.Exists(theFile.Filename))
				File.Delete(theFile.Filename);

			DicomFile saveCopy = new DicomFile(theFile.Filename, theFile.MetaInfo.Copy(), theFile.DataSet.Copy());

			theFile.ChangeTransferSyntax(syntax);

			theFile.Save(DicomWriteOptions.ExplicitLengthSequence);

			DicomFile newFile = new DicomFile(theFile.Filename);

			newFile.Load(DicomReadOptions.Default);

			newFile.ChangeTransferSyntax(saveCopy.TransferSyntax);

			Assert.IsFalse(newFile.DataSet.Equals(saveCopy.DataSet));

			Assert.IsTrue(newFile.DataSet.Contains(DicomTags.DerivationDescription));
			Assert.IsTrue(newFile.DataSet.Contains(DicomTags.LossyImageCompression));
			Assert.IsTrue(newFile.DataSet.Contains(DicomTags.LossyImageCompressionMethod));
			Assert.IsTrue(newFile.DataSet.Contains(DicomTags.LossyImageCompressionRatio));

			Assert.IsFalse(newFile.DataSet[DicomTags.DerivationDescription].IsEmpty);
			Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompression].IsEmpty);
			Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompressionMethod].IsEmpty);
			Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompressionRatio].IsEmpty);

			Assert.IsFalse(newFile.DataSet[DicomTags.DerivationDescription].IsNull);
			Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompression].IsNull);
			Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompressionMethod].IsNull);
			Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompressionRatio].IsNull);

			// Make copies of datasets, delete the tags that don't match, and ensure the same
			DicomAttributeCollection newDataSet = newFile.DataSet.Copy(true, true, true);
			DicomAttributeCollection oldDataSet = theFile.DataSet.Copy(true, true, true);

			oldDataSet.RemoveAttribute(DicomTags.PixelData);
			newDataSet.RemoveAttribute(DicomTags.PixelData);
			oldDataSet.RemoveAttribute(DicomTags.DerivationDescription);
			newDataSet.RemoveAttribute(DicomTags.DerivationDescription);
			oldDataSet.RemoveAttribute(DicomTags.LossyImageCompression);
			newDataSet.RemoveAttribute(DicomTags.LossyImageCompression);
			oldDataSet.RemoveAttribute(DicomTags.LossyImageCompressionMethod);
			newDataSet.RemoveAttribute(DicomTags.LossyImageCompressionMethod);
			oldDataSet.RemoveAttribute(DicomTags.LossyImageCompressionRatio);
			newDataSet.RemoveAttribute(DicomTags.LossyImageCompressionRatio);
			oldDataSet.RemoveAttribute(DicomTags.PhotometricInterpretation);
			newDataSet.RemoveAttribute(DicomTags.PhotometricInterpretation);

			List<DicomAttributeComparisonResult> results = new List<DicomAttributeComparisonResult>();

			bool check = oldDataSet.Equals(newDataSet, ref results);
			Assert.IsTrue(check, results.Count > 0 ? CollectionUtils.FirstElement(results).Details : string.Empty);
		}
Exemplo n.º 35
0
		public static void ExpectedFailureTest(TransferSyntax syntax, DicomFile theFile)
		{
			try
			{
				theFile.ChangeTransferSyntax(syntax);
			}
			catch (DicomCodecUnsupportedSopException)
			{
				return;
			}

			Assert.IsTrue(false, "Unexpected successfull compression of object.");
		}
Exemplo n.º 36
0
        private void ChangeSyntax(DicomTransferSyntax syntax, DicomCodecParams param = null)
        {
            var file = _file.ChangeTransferSyntax(syntax, param);

            OpenFile(file);
        }
        public static void LosslessImageTestWithBitsAllocatedConversion(TransferSyntax syntax, DicomFile theFile)
        {
            if (File.Exists(theFile.Filename))
            {
                File.Delete(theFile.Filename);
            }

            DicomFile saveCopy = new DicomFile(theFile.Filename, theFile.MetaInfo.Copy(), theFile.DataSet.Copy());

            theFile.ChangeTransferSyntax(syntax);

            theFile.Save(DicomWriteOptions.ExplicitLengthSequence);

            DicomFile newFile = new DicomFile(theFile.Filename);

            newFile.Load(DicomReadOptions.Default);

            newFile.ChangeTransferSyntax(saveCopy.TransferSyntax);

            string failureDescription;
            var    newPd = DicomPixelData.CreateFrom(newFile);
            var    oldPd = DicomPixelData.CreateFrom(saveCopy);

            bool result = Compare(newPd, oldPd, out failureDescription);

            Assert.IsFalse(result, failureDescription);

            Assert.IsFalse(newFile.DataSet.Equals(saveCopy.DataSet));

            DicomAttributeCollection newDataSet = newFile.DataSet.Copy(true, true, true);
            DicomAttributeCollection oldDataSet = theFile.DataSet.Copy(true, true, true);

            oldDataSet.RemoveAttribute(DicomTags.BitsAllocated);
            newDataSet.RemoveAttribute(DicomTags.BitsAllocated);
            oldDataSet.RemoveAttribute(DicomTags.PixelData);
            newDataSet.RemoveAttribute(DicomTags.PixelData);

            var results = new List <DicomAttributeComparisonResult>();

            bool check = oldDataSet.Equals(newDataSet, ref results);

            Assert.IsTrue(check, results.Count > 0 ? CollectionUtils.FirstElement(results).Details : string.Empty);

            for (int i = 0; i < oldPd.NumberOfFrames; i++)
            {
                var frame          = oldPd.GetFrame(i);
                var convertedFrame = DicomUncompressedPixelData.ToggleBitDepth(frame, frame.Length,
                                                                               oldPd.UncompressedFrameSize,
                                                                               oldPd.BitsStored, oldPd.BitsAllocated);
                var newFrame = newPd.GetFrame(i);

                int     pixelsVarying  = 0;
                decimal totalVariation = 0.0m;
                for (int j = 0; j < convertedFrame.Length; j++)
                {
                    if (convertedFrame[j] != newFrame[j])
                    {
                        pixelsVarying++;
                        totalVariation += Math.Abs(convertedFrame[i] - newFrame[i]);
                    }
                }

                if (pixelsVarying > 0)
                {
                    Assert.Fail(String.Format(
                                    "Tag (7fe0,0010) Pixel Data: {0} of {1} pixels varying, average difference: {2}",
                                    pixelsVarying, convertedFrame.Length, totalVariation / pixelsVarying));
                }
            }
        }
Exemplo n.º 38
0
		public static void LossyImageTest(TransferSyntax syntax, DicomFile theFile)
		{
			if (File.Exists(theFile.Filename))
				File.Delete(theFile.Filename);

			DicomFile saveCopy = new DicomFile(theFile.Filename, theFile.MetaInfo.Copy(), theFile.DataSet.Copy());

			theFile.ChangeTransferSyntax(syntax);

			theFile.Save(DicomWriteOptions.ExplicitLengthSequence);

			DicomFile newFile = new DicomFile(theFile.Filename);

			newFile.Load(DicomReadOptions.Default);

			newFile.ChangeTransferSyntax(saveCopy.TransferSyntax);

			Assert.IsFalse(newFile.DataSet.Equals(saveCopy.DataSet));

			Assert.IsTrue(newFile.DataSet.Contains(DicomTags.DerivationDescription));
			Assert.IsTrue(newFile.DataSet.Contains(DicomTags.LossyImageCompression));
			Assert.IsTrue(newFile.DataSet.Contains(DicomTags.LossyImageCompressionMethod));
			Assert.IsTrue(newFile.DataSet.Contains(DicomTags.LossyImageCompressionRatio));

			Assert.IsFalse(newFile.DataSet[DicomTags.DerivationDescription].IsEmpty);
			Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompression].IsEmpty);
			Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompressionMethod].IsEmpty);
			Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompressionRatio].IsEmpty);

			Assert.IsFalse(newFile.DataSet[DicomTags.DerivationDescription].IsNull);
			Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompression].IsNull);
			Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompressionMethod].IsNull);
			Assert.IsFalse(newFile.DataSet[DicomTags.LossyImageCompressionRatio].IsNull);

		}
Exemplo n.º 39
0
        public static void LosslessImageTestWithBitsAllocatedConversion(TransferSyntax syntax, DicomFile theFile)
        {
            if (File.Exists(theFile.Filename))
                File.Delete(theFile.Filename);

            DicomFile saveCopy = new DicomFile(theFile.Filename, theFile.MetaInfo.Copy(), theFile.DataSet.Copy());

            theFile.ChangeTransferSyntax(syntax);

            theFile.Save(DicomWriteOptions.ExplicitLengthSequence);

            DicomFile newFile = new DicomFile(theFile.Filename);

            newFile.Load(DicomReadOptions.Default);

            newFile.ChangeTransferSyntax(saveCopy.TransferSyntax);

            string failureDescription;
            var newPd = DicomPixelData.CreateFrom(newFile);
            var oldPd = DicomPixelData.CreateFrom(saveCopy);

            bool result = Compare(newPd, oldPd, out failureDescription);
            Assert.IsFalse(result, failureDescription);

            Assert.IsFalse(newFile.DataSet.Equals(saveCopy.DataSet));

            DicomAttributeCollection newDataSet = newFile.DataSet.Copy(true, true, true);
            DicomAttributeCollection oldDataSet = theFile.DataSet.Copy(true, true, true);

            oldDataSet.RemoveAttribute(DicomTags.BitsAllocated);
            newDataSet.RemoveAttribute(DicomTags.BitsAllocated);
            oldDataSet.RemoveAttribute(DicomTags.PixelData);
            newDataSet.RemoveAttribute(DicomTags.PixelData);

            var results = new List<DicomAttributeComparisonResult>();

            bool check = oldDataSet.Equals(newDataSet, ref results);
            Assert.IsTrue(check, results.Count > 0 ? CollectionUtils.FirstElement(results).Details : string.Empty);

            for (int i = 0; i < oldPd.NumberOfFrames; i++)
            {
                var frame = oldPd.GetFrame(i);
                var convertedFrame = DicomUncompressedPixelData.ToggleBitDepth(frame, frame.Length,
                                                                              oldPd.UncompressedFrameSize,
                                                                              oldPd.BitsStored, oldPd.BitsAllocated);
                var newFrame = newPd.GetFrame(i);

                int pixelsVarying = 0;
                decimal totalVariation = 0.0m;
                for (int j = 0; j < convertedFrame.Length; j++)
                    if (convertedFrame[j] != newFrame[j])
                    {
                        pixelsVarying++;
                        totalVariation += Math.Abs(convertedFrame[i] - newFrame[i]);
                    }

                if (pixelsVarying > 0)
                {
                    Assert.Fail(String.Format(
                        "Tag (7fe0,0010) Pixel Data: {0} of {1} pixels varying, average difference: {2}",
                        pixelsVarying, convertedFrame.Length, totalVariation/pixelsVarying));
                }
            }
        }
Exemplo n.º 40
0
        public void PartialFrameTest()
        {
            DicomFile file = new DicomFile("RlePartialFrameTest.dcm");

            SetupMultiframeXA(file.DataSet, 511, 511, 7);

            file.ChangeTransferSyntax(TransferSyntax.RleLossless);

            file.Save();

            DicomFile newFile = new DicomFile(file.Filename);

            newFile.Load(DicomReadOptions.StorePixelDataReferences);

            DicomPixelData pd;

            if (!newFile.TransferSyntax.Encapsulated)
                pd = new DicomUncompressedPixelData(newFile);
            else if (newFile.TransferSyntax.Equals(TransferSyntax.RleLossless))
                pd = new DicomCompressedPixelData(newFile);
            else
                throw new DicomCodecException("Unsupported transfer syntax: " + newFile.TransferSyntax);

            for (int i=0; i< pd.NumberOfFrames; i++)
            {
                pd.GetFrame(i);
            }
        }