Пример #1
0
        public static WindowLevel[] FromDataset(DcmDataset dataset)
        {
            List<WindowLevel> settings = new List<WindowLevel>();

            if (dataset.Contains(DicomTags.WindowCenter) && dataset.Contains(DicomTags.WindowWidth)) {
                string[] wc = dataset.GetDS(DicomTags.WindowCenter).GetValues();
                string[] ww = dataset.GetDS(DicomTags.WindowWidth).GetValues();

                if (wc.Length != ww.Length)
                    throw new DicomImagingException("Window Center count does not match Window Width count");

                string[] desc = null;
                if (dataset.Contains(DicomTags.WindowCenterWidthExplanation)) {
                    desc = dataset.GetLO(DicomTags.WindowCenterWidthExplanation).GetValues();
                }

                for (int i = 0; i < wc.Length; i++) {
                    double window;
                    double level;
                    if (!Double.TryParse(ww[i], out window) || !Double.TryParse(wc[i], out level))
                        throw new DicomImagingException("Unable to parse Window/Level [wc: {0}; ww: {1}]", wc[i], ww[i]);

                    string description = String.Empty;
                    if (desc != null && i < desc.Length)
                        description = desc[i];

                    settings.Add(new WindowLevel(description, window, level));
                }
            }

            return settings.ToArray();
        }
Пример #2
0
 /// <summary>
 /// Initializes new Basic Film Box
 /// </summary>
 /// <param name="session">Basic Film Session</param>
 /// <param name="sopInstance">SOP Instance UID</param>
 /// <param name="dataset">Dataset</param>
 public DcmFilmBox(DcmFilmSession session, DicomUID sopInstance, DcmDataset dataset)
 {
     _session = session;
     _sopInstance = sopInstance;
     _dataset = dataset;
     _boxes = new List<DcmImageBox>();
 }
Пример #3
0
 /// <summary>
 /// Initializes new Basic Image Box
 /// </summary>
 /// <param name="filmBox">Basic Film Box</param>
 /// <param name="sopClass">SOP Class UID</param>
 /// <param name="sopInstance">SOP Instance UID</param>
 public DcmImageBox(DcmFilmBox filmBox, DicomUID sopClass, DicomUID sopInstance)
 {
     _filmBox = filmBox;
     _sopClass = sopClass;
     _sopInstance = sopInstance;
     _dataset = new DcmDataset(DicomTransferSyntax.ImplicitVRLittleEndian);
 }
Пример #4
0
 /// <summary>
 /// Initializes new Basic Image Box
 /// </summary>
 /// <param name="filmBox">Basic Film Box</param>
 /// <param name="sopClass">SOP Class UID</param>
 /// <param name="sopInstance">SOP Instance UID</param>
 /// <param name="dataset">Dataset</param>
 public DcmImageBox(DcmFilmBox filmBox, DicomUID sopClass, DicomUID sopInstance, DcmDataset dataset)
 {
     _filmBox = filmBox;
     _sopClass = sopClass;
     _sopInstance = sopInstance;
     _dataset = dataset;
 }
Пример #5
0
 /// <summary>
 /// Initializes new Basic Film Box
 /// </summary>
 /// <param name="session">Basic Film Session</param>
 /// <param name="sopInstance">SOP Instance UID</param>
 public DcmFilmBox(DcmFilmSession session, DicomUID sopInstance)
 {
     _session = session;
     _sopInstance = sopInstance;
     _dataset = new DcmDataset(DicomTransferSyntax.ImplicitVRLittleEndian);
     _boxes = new List<DcmImageBox>();
 }
Пример #6
0
        private void LoadDataset(DcmDataset ds, Collection<Node> parent)
        {
            if (ds == null)
                return;

            foreach (DcmItem di in ds.Elements) {
                Image icon = LoadTreeViewAdvResourceImage("Leaf", di.VR.VR, Color.Blue);

                DicomNode dn = new DicomNode(icon, di);
                parent.Add(dn);

                if (di is DcmItemSequence) {
                    dn.Icon = LoadTreeViewAdvResourceImage("FolderClosed", "SQ", Color.Blue);

                    DcmItemSequence sq = di as DcmItemSequence;
                    foreach (DcmItemSequenceItem item in sq.SequenceItems) {
                        icon = LoadTreeViewAdvResourceImage("Folder", "", Color.Black);
                        DicomTagNode din = new DicomTagNode(icon, DicomTags.Item, item.StreamLength);
                        dn.Nodes.Add(din);
                        LoadDataset(item.Dataset, din.Nodes);
                        if (item.StreamLength == 0xffffffff) {
                            icon = LoadTreeViewAdvResourceImage("FolderClosed", "", Color.Black);
                            din.Nodes.Add(new DicomTagNode(icon, DicomTags.ItemDelimitationItem, 0));
                        }
                    }
                    if (sq.StreamLength == 0xffffffff) {
                        icon = LoadTreeViewAdvResourceImage("FolderClosed", "", Color.Black);
                        dn.Nodes.Add(new DicomTagNode(icon, DicomTags.SequenceDelimitationItem, 0));
                    }
                }
            }
        }
Пример #7
0
		public static XDocument ToXML(DcmDataset dataset, XDicomOptions options) {
			XDocument document = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
			XElement root = new XElement("dicom");
			LoadSequence(root, dataset.Elements, options);
			document.Add(root);
			return document;
		}
Пример #8
0
		public DcmPixelData(DcmDataset dataset) {
			_transferSyntax = dataset.InternalTransferSyntax;
			_lossy = dataset.GetString(DicomTags.LossyImageCompression, "00") != "00";
			_lossyMethod = dataset.GetString(DicomTags.LossyImageCompressionMethod, String.Empty);
			_lossyRatio = dataset.GetString(DicomTags.LossyImageCompressionRatio, String.Empty);
			_frames = dataset.GetInt32(DicomTags.NumberOfFrames, 1);
			_width = dataset.GetUInt16(DicomTags.Columns, 0);
			_height = dataset.GetUInt16(DicomTags.Rows, 0);
			_bitsStored = dataset.GetUInt16(DicomTags.BitsStored, 0);
			_bitsAllocated = dataset.GetUInt16(DicomTags.BitsAllocated, 0);
			_highBit = dataset.GetUInt16(DicomTags.HighBit, (ushort)(_bitsStored - 1));
			_samplesPerPixel = dataset.GetUInt16(DicomTags.SamplesPerPixel, 0);
			_pixelRepresentation = dataset.GetUInt16(DicomTags.PixelRepresentation, 0);
			_planarConfiguration = dataset.GetUInt16(DicomTags.PlanarConfiguration, 0);
			_photometricInterpretation = dataset.GetString(DicomTags.PhotometricInterpretation, String.Empty);
			_rescaleSlope = dataset.GetDouble(DicomTags.RescaleSlope, 1.0);
			_rescaleIntercept = dataset.GetDouble(DicomTags.RescaleIntercept, 0.0);
			_pixelDataItem = dataset.GetItem(DicomTags.PixelData);

			_hasPixelPadding = dataset.Contains(DicomTags.PixelPaddingValue);
			if (_hasPixelPadding) {
				DcmElement elem = dataset.GetElement(DicomTags.PixelPaddingValue);
				if (elem is DcmUnsignedShort)
					_pixelPaddingValue = (elem as DcmUnsignedShort).GetValue();
				else if (elem is DcmSignedShort) {
					_pixelPaddingValue = (elem as DcmSignedShort).GetValue();
				} else
					_pixelPaddingValue = MinimumDataValue;
			}
		}
Пример #9
0
        private static Expression<Func<Study, bool>> FilterByModality(DcmDataset query)
        {
            Expression<Func<Study, bool>> allMatch = p => true;

            var studyQuery = query.GetElement(DicomTags.ModalitiesInStudy);

            if (studyQuery == null)
                return allMatch;

            var valueString = studyQuery.GetValueString();

            if (String.IsNullOrWhiteSpace(valueString))
                return allMatch;

            var modalities = valueString.Replace(@"\\", @"\").Split('\\');

            if (modalities.Length == 1)
            {
                return s => s.ModalityAggregation.Contains(modalities[0]);
            }
            else
            {
                return s => s.Series.Any( series => modalities.Contains(series.PerformedModalityType));
            }
        }
Пример #10
0
 public static IPipeline Create(DcmDataset dataset, DcmPixelData pixelData)
 {
     PhotometricInterpretation pi = PhotometricInterpretation.Lookup(pixelData.PhotometricInterpretation);
     if (pi == PhotometricInterpretation.Monochrome1 || pi == PhotometricInterpretation.Monochrome2) {
         GenericGrayscalePipeline pipeline = new GenericGrayscalePipeline(pixelData.RescaleSlope, pixelData.RescaleIntercept, pixelData.BitsStored, pixelData.IsSigned);
         if (pi == PhotometricInterpretation.Monochrome1)
             pipeline.ColorMap = ColorTable.Monochrome1;
         else
             pipeline.ColorMap = ColorTable.Monochrome2;
         WindowLevel[] wl = WindowLevel.FromDataset(dataset);
         if (wl.Length > 0)
             pipeline.WindowLevel = wl[0];
         return pipeline;
     }
     else if (pi == PhotometricInterpretation.Rgb)
     {
         return new RgbColorPipeline();
     }
     else if (pi == PhotometricInterpretation.YbrFull || pi == PhotometricInterpretation.YbrFull422)
     {
         return new RgbColorPipeline();
     }
     else
     {
         throw new DicomImagingException("Unsupported pipeline photometric interpretation: {0}", pi.Value);
     }
 }
Пример #11
0
 public bool Match(DcmDataset dataset)
 {
     if (dataset.Contains(_tag)) {
         string value = dataset.GetValueString(_tag);
         return value.Contains(_value);
     }
     return false;
 }
Пример #12
0
		public void Transform(DcmDataset dataset) {
			if (_conditions != null)
				if (!_conditions.Match(dataset))
					return;

			foreach (IDicomTransformRule rule in _transformRules)
				rule.Transform(dataset);
		}
Пример #13
0
 private void Load(DcmDataset dataset, int frame)
 {
     Dataset = dataset;
     if (Dataset.InternalTransferSyntax.IsEncapsulated)
         Dataset.ChangeTransferSyntax(DicomTransferSyntax.ExplicitVRLittleEndian, null);
     DcmPixelData pixelData = new DcmPixelData(Dataset);
     _pixelData = PixelDataFactory.Create(pixelData, frame);
     _pipeline = PipelineFactory.Create(Dataset, pixelData);
     pixelData.Unload();
 }
Пример #14
0
        /// <summary>
        /// Initializes new Basic Film Session
        /// </summary>
        /// <param name="sessionClass">Color or Grayscale Basic Print Management UID</param>
        /// <param name="sopInstance">SOP Instance UID</param>
        /// <param name="dataset">Dataset</param>
        public DcmFilmSession(DicomUID sessionClass, DicomUID sopInstance, DcmDataset dataset)
        {
            _sessionClass = sessionClass;
            _sopInstance = sopInstance;
            _dataset = dataset;
            _boxes = new List<DcmFilmBox>();

            if (_sopInstance == null || _sopInstance.UID == String.Empty)
                _sopInstance = DicomUID.Generate();
        }
Пример #15
0
		/// <summary>
		/// Initializes new DICOM file format from dataset
		/// </summary>
		/// <param name="dataset">Dataset</param>
		public DicomFileFormat(DcmDataset dataset) {
			_metainfo = new DcmFileMetaInfo();
			_metainfo.FileMetaInformationVersion = DcmFileMetaInfo.Version;
			_metainfo.MediaStorageSOPClassUID = dataset.GetUID(DicomTags.SOPClassUID);
			_metainfo.MediaStorageSOPInstanceUID = dataset.GetUID(DicomTags.SOPInstanceUID);
			_metainfo.TransferSyntax = dataset.InternalTransferSyntax;
			_metainfo.ImplementationClassUID = Implementation.ClassUID;
			_metainfo.ImplementationVersionName = Implementation.Version;
			_metainfo.SourceApplicationEntityTitle = "";
			_dataset = dataset;
		}
Пример #16
0
        public static IQueryable<Series> GetMatchingSeries(MedicalISDataContext database, DcmDataset query)
        {
            var series = from s in database.Series select s;

            series = series.Where( FilterByStudyUid(query) );
            series = series.Where( FilterBySeriesUid(query) );
            series = series.Where( FilterBySeriesDate(query) );

            series.OrderBy(s => s.PerformedDateTime);

            return series;
        }
Пример #17
0
        private static Expression<Func<Patient, bool>> FilterByPatientsName(DcmDataset query)
        {
            Expression<Func<Patient, bool>> allMatch = p => true;

            var patientNameQuery = query.GetElement(DicomTags.PatientsName);

            if (patientNameQuery == null)
                return allMatch;

            var patientNameDicomFormatted = patientNameQuery.GetValueString();

            if (String.IsNullOrWhiteSpace(patientNameDicomFormatted))
                return allMatch;

            string[] lName;

            if (patientNameDicomFormatted.Contains("[^]"))
                lName = patientNameDicomFormatted.Split(new[] { "[^]" }, StringSplitOptions.None);
            else if (patientNameDicomFormatted.Contains("^"))
                lName = patientNameDicomFormatted.Split(new[] { "^" }, StringSplitOptions.None);
            else
                lName = patientNameDicomFormatted.Split(new[] { Properties.Settings.Default.PatientNameSplitCharacterForFind });

            var firstName = "";
            var lastName = "";

            if (lName.Length == 0)
                return allMatch;

            if (lName.Length >= 2)
            {
                firstName = lName[1];
                firstName = firstName.TrimEnd('*').Trim();
                firstName = firstName.Replace('*', '%');
            }

            if (lName.Length >= 1)
            {
                lastName = lName[0];
                lastName = lastName.TrimEnd('*').Trim();
                lastName = lastName.Replace('*', '%');
            }

            if (!firstName.StartsWith("\""))
                firstName += "%";
            if (!lastName.StartsWith("\""))
                lastName += "%";

            return p => SqlMethods.Like(p.FirstName, firstName) && SqlMethods.Like(p.LastName, lastName);
        }
Пример #18
0
        public void Decode(DcmDataset dataset, DcmPixelData oldPixelData, DcmPixelData newPixelData, DcmCodecParameters parameters)
        {
            DcmRleCodecParameters rleParams = parameters as DcmRleCodecParameters;

            if (rleParams == null)
                rleParams = GetDefaultParameters() as DcmRleCodecParameters;

            int pixelCount = oldPixelData.ImageWidth * oldPixelData.ImageHeight;
            int numberOfSegments = oldPixelData.BytesAllocated * oldPixelData.SamplesPerPixel;

            byte[] frameData = new byte[newPixelData.UncompressedFrameSize];

            for (int i = 0; i < oldPixelData.NumberOfFrames; i++)
            {
                IList<ByteBuffer> rleData = oldPixelData.GetFrameFragments(i);
                RLEDecoder decoder = new RLEDecoder(rleData);

                if (decoder.NumberOfSegments != numberOfSegments)
                    throw new DicomCodecException("Unexpected number of RLE segments!");

                for (int s = 0; s < numberOfSegments; s++)
                {
                    int sample = s / newPixelData.BytesAllocated;
                    int sabyte = s % newPixelData.BytesAllocated;

                    int pos, offset;

                    if (newPixelData.PlanarConfiguration == 0)
                    {
                        pos = sample * newPixelData.BytesAllocated;
                        offset = newPixelData.SamplesPerPixel * newPixelData.BytesAllocated;
                    }
                    else
                    {
                        pos = sample * newPixelData.BytesAllocated * pixelCount;
                        offset = newPixelData.BytesAllocated;
                    }

                    if (rleParams.ReverseByteOrder)
                        pos += sabyte;
                    else
                        pos += newPixelData.BytesAllocated - sabyte - 1;

                    decoder.DecodeSegment(s, frameData, pos, offset);
                }

                newPixelData.AddFrame(frameData);
            }
        }
Пример #19
0
        public static IQueryable<Patient> GetMatchingPatients(MedicalISDataContext database, DcmDataset query, bool anonymousOnly = false)
        {
            var patients = from p in database.Patients select p;

            if( anonymousOnly == false )
                patients = patients.Where(FilterByPatientsName(query));

            patients = patients.Where(FilterByPatientsId(query));
            patients = patients.Where(FilterByPatientsBirthDate(query));
            patients = patients.Where(FilterByStudyPerformedDate(query));
            patients = patients.Where(FilterByStudyModalityDate(query));

            patients = patients.OrderByDescending(p => p.Studies.Max(s => s.PerformedDateTime));

            return patients;
        }
Пример #20
0
		public bool Match(DcmDataset dataset) {
			if (_operator == DicomMatchOperator.Or) {
				foreach (IDicomMatchRule rule in _rules)
					if (rule.Match(dataset))
						return true;

				return false;
			}
			else {
				foreach (IDicomMatchRule rule in _rules)
					if (!rule.Match(dataset))
						return false;

				return true;
			}
		}
Пример #21
0
        private static Expression<Func<Series, bool>> FilterBySeriesDate(DcmDataset query)
        {
            Expression<Func<Series, bool>> allMatch = p => true;

            var studyQuery = query.GetElement(DicomTags.SeriesDate);

            if (studyQuery == null)
                return allMatch;

            var valueString = studyQuery.GetValueString();

            if (String.IsNullOrWhiteSpace(valueString))
                return allMatch;

            var dateTimeRange = DateTimeRangeQuery.Parse(valueString);

            return s => s.PerformedDateTime >= dateTimeRange.From && s.PerformedDateTime <= dateTimeRange.To;
        }
Пример #22
0
        private static Expression<Func<Study, bool>> FilterByPatientsBirthDate(DcmDataset query)
        {
            Expression<Func<Study, bool>> allMatch = p => true;

            var patientQuery = query.GetElement(DicomTags.PatientsBirthDate);

            if (patientQuery == null)
                return allMatch;

            var valueString = patientQuery.GetValueString();

            if (String.IsNullOrWhiteSpace(valueString))
                return allMatch;

            var dateTimeRange = DateTimeRangeQuery.Parse(valueString);

            return s => s.Patient.BirthDateTime >= dateTimeRange.From && s.Patient.BirthDateTime <= dateTimeRange.To;
        }
Пример #23
0
        private static Expression<Func<Patient, bool>> FilterByPatientsId(DcmDataset query)
        {
            Expression<Func<Patient, bool>> allMatch = p => true;

            var patientQuery = query.GetElement(DicomTags.PatientID);

            if (patientQuery == null)
                return allMatch;

            var valueString = patientQuery.GetValueString();

            if (String.IsNullOrWhiteSpace(valueString))
                return allMatch;

            if (valueString.EndsWith("*"))
                return p => p.ExternalPatientID.StartsWith(valueString.Trim('*'));
            else
                return p => p.ExternalPatientID == valueString;
        }
Пример #24
0
        private static Expression<Func<Study, bool>> FilterByAccessionNumber(DcmDataset query)
        {
            Expression<Func<Study, bool>> allMatch = p => true;

            var studyQuery = query.GetElement(DicomTags.AccessionNumber);

            if (studyQuery == null)
                return allMatch;

            var valueString = studyQuery.GetValueString();

            if (String.IsNullOrWhiteSpace(valueString))
                return allMatch;

            if (valueString.EndsWith("*"))
                return s => s.AccessionNumber.StartsWith(valueString.Trim('*'));
            else
                return s => s.AccessionNumber == valueString;
        }
Пример #25
0
        public static IQueryable<Study> GetMatchingStudies(MedicalISDataContext database, DcmDataset query, bool isAnonymousQuery )
        {
            var studies = from s in database.Studies select s;

            if (!isAnonymousQuery)
                studies = studies.Where( FilterByPatientsName(query) );

            studies = studies.Where( FilterByPatientsId(query) );
            studies = studies.Where( FilterByPatientsBirthDate(query) );

            studies = studies.Where( FilterByStudyUid(query) );
            studies = studies.Where( FilterByStudyDate(query) );
            studies = studies.Where( FilterByAccessionNumber(query) );

            studies = studies.Where( FilterByModality(query) );

            studies.OrderBy(s => s.PerformedDateTime);

            return studies;
        }
Пример #26
0
        private static Expression<Func<Series, bool>> FilterByStudyUid(DcmDataset query)
        {
            Expression<Func<Series, bool>> allMatch = p => true;

            var seriesQuery = query.GetElement(DicomTags.StudyInstanceUID);

            if (seriesQuery == null)
                return allMatch;

            var valueString = seriesQuery.GetValueString();

            if (String.IsNullOrWhiteSpace(valueString))
                return allMatch;

            if (valueString.EndsWith("*"))
            {
                return s => s.StudyInstanceUid.StartsWith(valueString.Trim('*'));
            }
            else
            {
                return s => s.StudyInstanceUid == valueString;
            }
        }
Пример #27
0
		protected override void OnReceiveNCreateRequest(byte presentationID, ushort messageID, 
			DicomUID affectedClass, DicomUID affectedInstance, DcmDataset dataset) {
			DicomUID sopClass = Associate.GetAbstractSyntax(presentationID);

			if (affectedClass == DicomUID.BasicFilmSessionSOPClass) {
				if (_session != null) {
					Log.Error("{0} -> Attempted to create second Basic Film Session on association", LogID);
					SendAbort(DcmAbortSource.ServiceProvider, DcmAbortReason.NotSpecified);
					return;
				}

				_session = new DcmFilmSession(sopClass, affectedInstance, dataset);

				SendNCreateResponse(presentationID, messageID, affectedClass, _session.SOPInstanceUID, null, DcmStatus.Success);
				return;
			}

			if (affectedClass == DicomUID.BasicFilmBoxSOPClass) {
				if (_session == null) {
					Log.Error("{0} -> A Basic Film Session does not exist for this association", LogID);
					SendAbort(DcmAbortSource.ServiceProvider, DcmAbortReason.NotSpecified);
					return;
				}

				DcmFilmBox box = _session.CreateFilmBox(affectedInstance, dataset);
				if (!box.Initialize()) {
					SendAbort(DcmAbortSource.ServiceProvider, DcmAbortReason.NotSpecified);
					return;
				}

				SendNCreateResponse(presentationID, messageID, affectedClass, box.SOPInstanceUID, dataset, DcmStatus.Success);
				return;
			}

			SendAbort(DcmAbortSource.ServiceProvider, DcmAbortReason.NotSpecified);
		}
Пример #28
0
 protected void SendNSetResponse(byte presentationID, ushort messageIdRespondedTo, DicomUID affectedClass, DicomUID affectedInstance,
     DcmDataset dataset, DcmStatus status)
 {
     DcmCommand command = new DcmCommand();
     command.AffectedSOPClassUID = affectedClass;
     command.CommandField = DcmCommandField.NSetResponse;
     command.MessageIDBeingRespondedTo = messageIdRespondedTo;
     command.HasDataset = (dataset != null);
     command.Status = status;
     command.AffectedSOPInstanceUID = affectedInstance;
     Log.Info("{0} -> N-Set response [id: {1}; class: {2}]: {3}", LogID, messageIdRespondedTo, affectedClass.Description, status);
     SendDimse(presentationID, command, dataset);
 }
Пример #29
0
 protected void SendNSetRequest(byte presentationID, ushort messageID, DicomUID requestedClass, DicomUID requestedInstance, DcmDataset dataset)
 {
     DcmCommand command = new DcmCommand();
     command.RequestedSOPClassUID = requestedClass;
     command.CommandField = DcmCommandField.NSetRequest;
     command.MessageID = messageID;
     command.HasDataset = (dataset != null);
     command.RequestedSOPInstanceUID = requestedInstance;
     Log.Info("{0} -> N-Set request [pc: {1}; id: {2}; class: {3}]", LogID, presentationID, messageID, requestedClass.Description);
     SendDimse(presentationID, command, dataset);
 }
Пример #30
0
 protected void SendNEventReportRequest(byte presentationID, ushort messageID, DicomUID affectedClass, DicomUID affectedInstance, 
     ushort eventTypeID, DcmDataset dataset)
 {
     DcmCommand command = new DcmCommand();
     command.AffectedSOPClassUID = affectedClass;
     command.CommandField = DcmCommandField.NEventReportRequest;
     command.MessageID = messageID;
     command.HasDataset = (dataset != null);
     command.AffectedSOPInstanceUID = affectedInstance;
     command.EventTypeID = eventTypeID;
     Log.Info("{0} -> N-EventReport request [pc: {1}; id: {2}; class: {3}; event: {4:x4}]",
         LogID, presentationID, messageID, affectedClass.Description, eventTypeID);
     SendDimse(presentationID, command, dataset);
 }