Example #1
0
        public void SetupRequiredMathMrtData(DicomTypes.RequiredMathMrtData data, uint rows, uint columns, uint frames, byte[] pixelArray)
        {
            dicomFile.DataSet[DicomTags.SliceThickness].SetStringValue(data.SliceThickness);
            dicomFile.DataSet[DicomTags.SpacingBetweenSlices].SetStringValue(data.SpacingBetweenSlices);

            dicomFile.DataSet[DicomTags.ImagePositionPatient].SetString(0, data.ImagePositionPatient0);
            dicomFile.DataSet[DicomTags.ImagePositionPatient].SetString(1, data.ImagePositionPatient1);
            dicomFile.DataSet[DicomTags.ImagePositionPatient].SetString(2, data.ImagePositionPatient2);

            dicomFile.DataSet[DicomTags.ImageOrientationPatient].SetString(0, data.ImageOrientationPatient0);
            dicomFile.DataSet[DicomTags.ImageOrientationPatient].SetString(1, data.ImageOrientationPatient1);
            dicomFile.DataSet[DicomTags.ImageOrientationPatient].SetString(2, data.ImageOrientationPatient2);
            dicomFile.DataSet[DicomTags.ImageOrientationPatient].SetString(3, data.ImageOrientationPatient3);
            dicomFile.DataSet[DicomTags.ImageOrientationPatient].SetString(4, data.ImageOrientationPatient4);
            dicomFile.DataSet[DicomTags.ImageOrientationPatient].SetString(5, data.ImageOrientationPatient5);


            dicomFile.DataSet[DicomTags.SamplesPerPixel].SetStringValue(data.SamplesPerPixel);


            dicomFile.DataSet[DicomTags.Rows].SetUInt32(0, rows);
            dicomFile.DataSet[DicomTags.Columns].SetUInt32(0, columns);
            dicomFile.DataSet[DicomTags.PixelSpacing].SetString(0, data.PixelSpacing0);
            dicomFile.DataSet[DicomTags.PixelSpacing].SetString(1, data.PixelSpacing1);
            dicomFile.DataSet[DicomTags.PixelRepresentation].SetStringValue(data.PixelRepresentation);

            dicomFile.DataSet[DicomTags.BitsAllocated].SetStringValue(data.BitsAllocated);
            dicomFile.DataSet[DicomTags.BitsStored].SetStringValue(data.BitsStored);
            dicomFile.DataSet[DicomTags.HighBit].SetStringValue(data.HighBit);

            uint length = rows * columns * frames;

            if (length % 2 == 1)
            {
                length++;
            }
            DicomAttributeOW pixels = new DicomAttributeOW(DicomTags.PixelData);

            pixelArray[length - 1] = 0x00;

            pixels.Values = pixelArray;

            dicomFile.DataSet[DicomTags.PixelData] = pixels;
        }
Example #2
0
        public DicomReadStatus Read(DicomTag stopAtTag, DicomReadOptions options)
        {
            if (stopAtTag == null)
            {
                stopAtTag = new DicomTag(0xFFFFFFFF, "Bogus Tag", "BogusTag", DicomVr.UNvr, false, 1, 1, false);
            }

            // Counters:
            //  _remain - bytes remaining in stream
            //  _bytes - estimates bytes to end of dataset
            //  _read - number of bytes read from stream
            try
            {
                BytesNeeded = 0;
                _remain     = _stream.Length - _stream.Position;

                while (_remain > 0)
                {
                    if (_inGroup2 && BytesRead >= _endGroup2)
                    {
                        _inGroup2 = false;
                        // Only change if we're still reading the meta info
                        if (Dataset.StartTagValue < DicomTags.TransferSyntaxUid)
                        {
                            TransferSyntax group2Syntax =
                                TransferSyntax.GetTransferSyntax(
                                    Dataset[DicomTags.TransferSyntaxUid].GetString(0, String.Empty));
                            if (group2Syntax == null)
                            {
                                throw new DicomException("Unsupported transfer syntax in group 2 elements");
                            }
                            TransferSyntax = group2Syntax;
                        }
                    }
                    uint tagValue;
                    if (LastTagRead == null)
                    {
                        if (_remain < 4)
                        {
                            return(NeedMoreData(4));
                        }

                        _pos = _stream.Position;
                        ushort g = _reader.ReadUInt16();
                        ushort e = _reader.ReadUInt16();
                        tagValue = DicomTag.GetTagValue(g, e);
                        if (DicomTag.IsPrivateGroup(g) && e > 0x00ff)
                        {
                            SaveTagRead = LastTagRead = DicomTagDictionary.GetDicomTag(g, e) ??
                                                        new DicomTag((uint)g << 16 | e, "Private Tag", "PrivateTag", DicomVr.UNvr, false, 1, uint.MaxValue, false);
                        }
                        else
                        {
                            if (e == 0x0000)
                            {
                                SaveTagRead = LastTagRead = new DicomTag((uint)g << 16 | e, "Group Length", "GroupLength", DicomVr.ULvr, false, 1, 1, false);
                            }
                            else
                            {
                                SaveTagRead = LastTagRead = DicomTagDictionary.GetDicomTag(g, e) ??
                                                            new DicomTag((uint)g << 16 | e, "Private Tag", "PrivateTag", DicomVr.UNvr, false, 1, uint.MaxValue, false);
                            }
                        }
                        _remain        -= 4;
                        BytesEstimated += 4;
                        BytesRead      += 4;
                    }
                    else
                    {
                        tagValue = LastTagRead.TagValue;
                    }

                    if ((tagValue >= stopAtTag.TagValue) &&
                        (_sqrs.Count == 0))                        // only exit in root message when after stop tag
                    {
                        if (_inGroup2 && tagValue > 0x0002FFFF)
                        {
                            if (_endGroup2 != BytesRead - 4)
                            {
                                Platform.Log(LogLevel.Debug, "File Meta Info Length, {0}, not equal to actual bytes read in file, {1}, overwriting length.",
                                             EndGroupTwo, BytesRead - 4);
                                _endGroup2 = BytesRead - 4;
                            }
                            _inGroup2 = false;
                        }
                        EncounteredStopTag = true;
                        return(DicomReadStatus.Success);
                    }

                    bool twoByteLength;
                    if (_vr == null)
                    {
                        if (_syntax.ExplicitVr)
                        {
                            if (LastTagRead == DicomTag.Item ||
                                LastTagRead == DicomTag.ItemDelimitationItem ||
                                LastTagRead == DicomTag.SequenceDelimitationItem)
                            {
                                _vr           = DicomVr.NONE;
                                twoByteLength = _vr.Is16BitLengthField;
                            }
                            else
                            {
                                if (_remain < 2)
                                {
                                    return(NeedMoreData(2));
                                }

                                string vr = new string(_reader.ReadChars(2));
                                _vr             = DicomVr.GetVR(vr);
                                twoByteLength   = _vr.Is16BitLengthField;
                                _remain        -= 2;
                                BytesEstimated += 2;
                                BytesRead      += 2;
                                if (LastTagRead.VR.Equals(DicomVr.UNvr))
                                {
                                    LastTagRead = new DicomTag(LastTagRead.TagValue, "Private Tag", "PrivateTag", _vr, false, 1, uint.MaxValue, false);
                                    if (vr.Equals("??"))
                                    {
                                        twoByteLength = true;
                                    }
                                }
                                else if (!LastTagRead.VR.Equals(_vr))
                                {
                                    if (!vr.Equals("  "))
                                    {
                                        DicomTag tag =
                                            new DicomTag(LastTagRead.TagValue, LastTagRead.Name, LastTagRead.VariableName, _vr, LastTagRead.MultiVR,
                                                         LastTagRead.VMLow, LastTagRead.VMHigh,
                                                         LastTagRead.Retired);
                                        LastTagRead = tag;

                                        ;                                         // TODO, log something
                                    }
                                }
                            }
                        }
                        else
                        {
                            _vr           = LastTagRead.VR;
                            twoByteLength = _vr.Is16BitLengthField;
                        }

                        if (_vr == DicomVr.UNvr)
                        {
                            if (LastTagRead.IsPrivate)
                            {
                                if (LastTagRead.Element <= 0x00ff && LastTagRead.Element >= 0x0010)
                                {
                                    // Reset the tag with the right VR and a more descriptive name.
                                    LastTagRead = new DicomTag(LastTagRead.TagValue, "Private Creator Code", "PrivateCreatorCode", DicomVr.LOvr, false, 1, uint.MaxValue, false);

                                    // private creator id
                                    // Only set the VR to LO for Implicit VR, if we do it for
                                    // Explicit VR syntaxes, we would incorrectly read the tag
                                    // length below.
                                    if (!_syntax.ExplicitVr)
                                    {
                                        _vr = DicomVr.LOvr;
                                    }
                                }
                                else if (_stream.CanSeek && Flags.IsSet(options, DicomReadOptions.AllowSeekingForContext))
                                {
                                    // attempt to identify private sequence by checking if the tag has
                                    // an undefined length
                                    long pos = _stream.Position;

                                    int bytesToCheck = _syntax.ExplicitVr ? 6 : 4;

                                    if (_remain >= bytesToCheck)
                                    {
                                        if (_syntax.ExplicitVr)
                                        {
                                            _reader.ReadUInt16();
                                        }

                                        uint l = _reader.ReadUInt32();
                                        if (l == _undefinedLength)
                                        {
                                            _vr = DicomVr.SQvr;
                                        }
                                    }
                                    _stream.Position = pos;
                                }
                            }
                        }
                    }
                    else
                    {
                        twoByteLength = _vr.Is16BitLengthField;
                    }

                    // Read the value length
                    if (_len == _undefinedLength)
                    {
                        if (_syntax.ExplicitVr)
                        {
                            if (LastTagRead == DicomTag.Item ||
                                LastTagRead == DicomTag.ItemDelimitationItem ||
                                LastTagRead == DicomTag.SequenceDelimitationItem)
                            {
                                if (_remain < 4)
                                {
                                    return(NeedMoreData(4));
                                }

                                _len            = _reader.ReadUInt32();
                                _remain        -= 4;
                                BytesEstimated += 4;
                                BytesRead      += 4;
                            }
                            else
                            {
                                if (twoByteLength)
                                {
                                    if (_remain < 2)
                                    {
                                        return(NeedMoreData(2));
                                    }

                                    _len            = _reader.ReadUInt16();
                                    _remain        -= 2;
                                    BytesEstimated += 2;
                                    BytesRead      += 2;
                                }
                                else
                                {
                                    if (_remain < 6)
                                    {
                                        return(NeedMoreData(6));
                                    }

                                    _reader.ReadByte();
                                    _reader.ReadByte();
                                    _len            = _reader.ReadUInt32();
                                    _remain        -= 6;
                                    BytesEstimated += 6;
                                    BytesRead      += 6;
                                }
                            }
                        }
                        else
                        {
                            if (_remain < 4)
                            {
                                return(NeedMoreData(4));
                            }

                            _len            = _reader.ReadUInt32();
                            _remain        -= 4;
                            BytesEstimated += 4;
                            BytesRead      += 4;
                        }

                        if ((_len != _undefinedLength) &&
                            !_vr.Equals(DicomVr.SQvr) &&
                            !(LastTagRead.Equals(DicomTag.Item) &&
                              _fragment == null))
                        {
                            BytesEstimated += _len;
                        }
                    }

                    // If we have a private creator code, set the VR to LO, because
                    // that is what it is.  We must do this after we read the length
                    // so that the 32 bit length is read properly.
                    if ((LastTagRead.IsPrivate) &&
                        (_vr.Equals(DicomVr.UNvr)) &&
                        (LastTagRead.Element <= 0x00ff))
                    {
                        _vr = DicomVr.LOvr;
                    }

                    if (_fragment != null)
                    {
                        // In the middle of parsing pixels
                        if (LastTagRead == DicomTag.Item)
                        {
                            if (_remain < _len)
                            {
                                return(NeedMoreData(_remain - _len));
                            }

                            if (Flags.IsSet(options, DicomReadOptions.StorePixelDataReferences) &&
                                _fragment.HasOffsetTable)
                            {
                                FileReference reference = new FileReference(StreamOpener, _stream.Position, _len, _endian, DicomVr.OBvr);
                                DicomFragment fragment  = new DicomFragment(reference);
                                _fragment.AddFragment(fragment);
                                if (_stream.CanSeek)
                                {
                                    _stream.Seek(_len, SeekOrigin.Current);
                                }
                                else
                                {
                                    ConsumeStreamBytes(_stream, _len);
                                }
                            }
                            else
                            {
                                ByteBuffer data = new ByteBuffer(_endian, _len);
                                data.CopyFrom(_stream, (int)_len);

                                if (!_fragment.HasOffsetTable)
                                {
                                    _fragment.SetOffsetTable(data);
                                }
                                else
                                {
                                    DicomFragment fragment = new DicomFragment(data);
                                    _fragment.AddFragment(fragment);
                                }
                            }

                            _remain   -= _len;
                            BytesRead += _len;
                        }
                        else if (LastTagRead == DicomTag.SequenceDelimitationItem)
                        {
                            if (_sqrs.Count > 0)
                            {
                                SequenceRecord           rec = _sqrs.Peek();
                                DicomAttributeCollection ds  = rec.Current;

                                ds[_fragment.Tag] = _fragment;

                                if (rec.Curlen != _undefinedLength)
                                {
                                    long end = rec.Curpos + rec.Curlen;
                                    if (_stream.Position >= end)
                                    {
                                        rec.Current = null;
                                    }
                                }
                            }
                            else
                            {
                                Dataset[_fragment.Tag] = _fragment;
                            }

                            _fragment = null;
                        }
                        else
                        {
                            Platform.Log(LogLevel.Error, "Encountered unexpected tag in stream: {0}", LastTagRead.ToString());
                            // unexpected tag
                            return(DicomReadStatus.UnknownError);
                        }
                    }
                    else if (_sqrs.Count > 0 &&
                             (LastTagRead == DicomTag.Item ||
                              LastTagRead == DicomTag.ItemDelimitationItem ||
                              LastTagRead == DicomTag.SequenceDelimitationItem))
                    {
                        SequenceRecord rec = _sqrs.Peek();

                        if (LastTagRead.Equals(DicomTag.Item))
                        {
                            if (_len != _undefinedLength)
                            {
                                if (_len > _remain)
                                {
                                    return(NeedMoreData(_remain - _len));
                                }
                            }

                            DicomSequenceItem ds;

                            if (rec.Tag.TagValue.Equals(DicomTags.DirectoryRecordSequence))
                            {
                                DirectoryRecordSequenceItem dr = new DirectoryRecordSequenceItem
                                {
                                    Offset = (uint)_pos
                                };

                                ds = dr;
                            }
                            else
                            {
                                ds = new DicomSequenceItem();
                            }

                            rec.Current = ds;
                            if (rec.Tag.VR.Equals(DicomVr.UNvr))
                            {
                                DicomTag tag = new DicomTag(rec.Tag.TagValue, rec.Tag.Name,
                                                            rec.Tag.VariableName, DicomVr.SQvr, rec.Tag.MultiVR, rec.Tag.VMLow,
                                                            rec.Tag.VMHigh, rec.Tag.Retired);
                                rec.Parent[tag].AddSequenceItem(ds);
                            }
                            else
                            {
                                rec.Parent[rec.Tag].AddSequenceItem(ds);
                            }

                            // Specific character set is inherited, save it.  It will be overwritten
                            // if a new value of the tag is encountered in the sequence.
                            rec.Current.SpecificCharacterSet = rec.Parent.SpecificCharacterSet;

                            // save the sequence length
                            rec.Curpos = _pos + 8;
                            rec.Curlen = _len;

                            _sqrs.Pop();
                            _sqrs.Push(rec);

                            if (_len != _undefinedLength)
                            {
                                ByteBuffer data = new ByteBuffer(_endian, _len);
                                data.CopyFrom(_stream, (int)_len);
                                data.Stream.Position = 0;
                                _remain   -= _len;
                                BytesRead += _len;

                                DicomStreamReader idsr = new DicomStreamReader(data.Stream)
                                {
                                    Dataset        = ds,
                                    TransferSyntax = rec.Tag.VR.Equals(DicomVr.UNvr)
                                                                                                         ? TransferSyntax.ImplicitVrLittleEndian
                                                                                                         : _syntax,
                                    StreamOpener = StreamOpener
                                };
                                DicomReadStatus stat = idsr.Read(null, options & ~DicomReadOptions.StorePixelDataReferences);
                                if (stat != DicomReadStatus.Success)
                                {
                                    Platform.Log(LogLevel.Error, "Unexpected parsing error ({0}) when reading sequence attribute: {1}.", stat, rec.Tag.ToString());
                                    return(stat);
                                }
                            }
                        }
                        else if (LastTagRead == DicomTag.ItemDelimitationItem)
                        {
                        }
                        else if (LastTagRead == DicomTag.SequenceDelimitationItem)
                        {
                            SequenceRecord rec2 = _sqrs.Pop();
                            if (rec2.Current == null)
                            {
                                rec2.Parent[rec.Tag].SetNullValue();
                            }
                        }

                        if (rec.Len != _undefinedLength)
                        {
                            long end = rec.Pos + 8 + rec.Len;
                            if (_syntax.ExplicitVr)
                            {
                                end += 2 + 2;
                            }
                            if (_stream.Position >= end)
                            {
                                _sqrs.Pop();
                            }
                        }
                    }
                    else
                    {
                        if (_len == _undefinedLength)
                        {
                            if (_vr.Equals(DicomVr.UNvr))
                            {
                                if (!_syntax.ExplicitVr)
                                {
                                    _vr         = DicomVr.SQvr;
                                    LastTagRead = LastTagRead.IsPrivate
                                                                                ? new DicomTag(LastTagRead.TagValue, "Private Tag", "PrivateTag", DicomVr.SQvr, false, 1, uint.MaxValue, false)
                                                                                : new DicomTag(LastTagRead.TagValue, "Unknown Tag", "UnknownTag", DicomVr.SQvr, false, 1, uint.MaxValue, false);
                                }
                                else
                                {
                                    // To handle this case, we'd have to add a new mechanism to transition the parser to implicit VR parsing,
                                    // and then return back to implicit once the parsing of the SQ is complete.
                                    Platform.Log(LogLevel.Error,
                                                 "Encountered unknown tag {0}, encoded as undefined length in an Explicit VR transfer syntax at offset {1}.  Unable to parse.",
                                                 LastTagRead, _stream.Position);
                                    return(DicomReadStatus.UnknownError);
                                }
                            }

                            if (_vr.Equals(DicomVr.SQvr))
                            {
                                SequenceRecord rec = new SequenceRecord
                                {
                                    Parent = _sqrs.Count > 0
                                                                                                     ? _sqrs.Peek().Current
                                                                                                     : Dataset,
                                    Current = null,
                                    Tag     = LastTagRead,
                                    Len     = _undefinedLength
                                };

                                _sqrs.Push(rec);
                            }
                            else
                            {
                                _fragment = new DicomFragmentSequence(LastTagRead);
                            }
                        }
                        else
                        {
                            if (_vr.Equals(DicomVr.SQvr))
                            {
                                if (_len == 0)
                                {
                                    DicomAttributeCollection ds;
                                    if (_sqrs.Count > 0)
                                    {
                                        SequenceRecord rec = _sqrs.Peek();
                                        ds = rec.Current;
                                    }
                                    else
                                    {
                                        ds = Dataset;
                                    }

                                    ds[LastTagRead].SetNullValue();
                                }
                                else
                                {
                                    SequenceRecord rec = new SequenceRecord
                                    {
                                        Len    = _len,
                                        Pos    = _pos,
                                        Tag    = LastTagRead,
                                        Parent = _sqrs.Count > 0
                                                                                                             ? _sqrs.Peek().Current
                                                                                                             : Dataset
                                    };

                                    _sqrs.Push(rec);
                                }
                            }
                            else
                            {
                                if (_remain < _len)
                                {
                                    return(NeedMoreData(_len - _remain));
                                }

                                if ((LastTagRead.TagValue == DicomTags.PixelData) &&
                                    Flags.IsSet(options, DicomReadOptions.DoNotStorePixelDataInDataSet))
                                {
                                    // Skip PixelData !!
                                    if (_stream.CanSeek)
                                    {
                                        _stream.Seek((int)_len, SeekOrigin.Current);
                                    }
                                    else
                                    {
                                        ConsumeStreamBytes(_stream, _len);
                                    }

                                    _remain   -= _len;
                                    BytesRead += _len;
                                }
                                else if ((LastTagRead.TagValue == DicomTags.PixelData) &&
                                         Flags.IsSet(options, DicomReadOptions.StorePixelDataReferences))
                                {
                                    var reference = new FileReference(StreamOpener, _stream.Position, _len, _endian, LastTagRead.VR);
                                    if (_stream.CanSeek)
                                    {
                                        _stream.Seek((int)_len, SeekOrigin.Current);
                                    }
                                    else
                                    {
                                        ConsumeStreamBytes(_stream, _len);
                                    }

                                    DicomAttribute elem;
                                    if (LastTagRead.VR.Equals(DicomVr.OWvr))
                                    {
                                        elem = new DicomAttributeOW(LastTagRead, reference);
                                    }
                                    else if (LastTagRead.VR.Equals(DicomVr.OBvr))
                                    {
                                        elem = new DicomAttributeOB(LastTagRead, reference);
                                    }
                                    else if (LastTagRead.VR.Equals(DicomVr.ODvr))
                                    {
                                        elem = new DicomAttributeOD(LastTagRead, reference);
                                    }
                                    else
                                    {
                                        elem = new DicomAttributeOF(LastTagRead, reference);
                                    }

                                    if (_sqrs.Count > 0)
                                    {
                                        SequenceRecord           rec = _sqrs.Peek();
                                        DicomAttributeCollection ds  = rec.Current;

                                        ds[LastTagRead] = elem;

                                        if (rec.Curlen != _undefinedLength)
                                        {
                                            long end = rec.Curpos + rec.Curlen;
                                            if (_stream.Position >= end)
                                            {
                                                rec.Current = null;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        Dataset[LastTagRead] = elem;
                                    }

                                    _remain   -= _len;
                                    BytesRead += _len;
                                }
                                else
                                {
                                    ByteBuffer bb = new ByteBuffer(_len);
                                    // If the tag is impacted by specific character set,
                                    // set the encoding properly.
                                    if (LastTagRead.VR.SpecificCharacterSet)
                                    {
                                        if (_sqrs.Count > 0)
                                        {
                                            SequenceRecord rec = _sqrs.Peek();
                                            bb.SpecificCharacterSet = rec.Current.SpecificCharacterSet;
                                        }
                                        else
                                        {
                                            bb.SpecificCharacterSet = Dataset.SpecificCharacterSet;
                                        }
                                    }
                                    if (LastTagRead.VR.Equals(DicomVr.UNvr) &&
                                        !SaveTagRead.VR.Equals(DicomVr.UNvr) &&
                                        !SaveTagRead.VR.Equals(DicomVr.SQvr) &&
                                        Flags.IsSet(options, DicomReadOptions.UseDictionaryForExplicitUN))
                                    {
                                        LastTagRead = SaveTagRead;
                                        bb.Endian   = Endian.Little;
                                    }
                                    else
                                    {
                                        bb.Endian = _endian;
                                    }

                                    bb.CopyFrom(_stream, (int)_len);

                                    DicomAttribute elem = LastTagRead.CreateDicomAttribute(bb);

                                    _remain   -= _len;
                                    BytesRead += _len;

                                    if (_sqrs.Count > 0)
                                    {
                                        SequenceRecord           rec = _sqrs.Peek();
                                        DicomAttributeCollection ds  = rec.Current;

                                        if (elem.Tag.TagValue == DicomTags.SpecificCharacterSet)
                                        {
                                            ds.SpecificCharacterSet = elem.ToString();
                                        }

                                        if (LastTagRead.Element == 0x0000)
                                        {
                                            if (Flags.IsSet(options, DicomReadOptions.KeepGroupLengths))
                                            {
                                                ds[LastTagRead] = elem;
                                            }
                                        }
                                        else
                                        {
                                            ds[LastTagRead] = elem;
                                        }

                                        if (rec.Curlen != _undefinedLength)
                                        {
                                            long end = rec.Curpos + rec.Curlen;
                                            if (_stream.Position >= end)
                                            {
                                                rec.Current = null;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (LastTagRead.TagValue == DicomTags.FileMetaInformationGroupLength)
                                        {
                                            // Save the end of the group 2 elements, so that we can automatically
                                            // check and change our transfer syntax when needed.
                                            _inGroup2 = true;
                                            uint group2Len;
                                            elem.TryGetUInt32(0, out group2Len);
                                            _endGroup2 = BytesRead + group2Len;
                                        }
                                        else if (LastTagRead.TagValue == DicomTags.SpecificCharacterSet)
                                        {
                                            Dataset.SpecificCharacterSet = elem.ToString();
                                        }

                                        if (LastTagRead.Element == 0x0000)
                                        {
                                            if (Flags.IsSet(options, DicomReadOptions.KeepGroupLengths))
                                            {
                                                Dataset[LastTagRead] = elem;
                                            }
                                        }
                                        else
                                        {
                                            Dataset[LastTagRead] = elem;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    LastTagRead = null;
                    _vr         = null;
                    _len        = _undefinedLength;
                }
                return(DicomReadStatus.Success);
            }
            catch (EndOfStreamException e)
            {
                // should never happen
                Platform.Log(LogLevel.Error, "Unexpected exception when reading file: {0}", e.ToString());
                return(DicomReadStatus.UnknownError);
            }
        }
        public DicomFile Serialize(SegmentationSerializerCallback callback)
        {
            Platform.CheckForNullReference(callback, "callback");

            Debug.Assert(!_segDocument.Saved, "Cannot serialize previously saved document");

            // TODO: validate that all Segs are coming from the same study!

            IPresentationImage firstIPresentationImage = null;
            if (_segDocument.Segs != null)
            {
                var oneSeg = _segDocument.Segs.FirstOrDefault(item => item != null && item.SegGraphics != null && item.SegGraphics.OfType<PolygonalRoiSegGraphic>().Any());
                if (oneSeg != null)
                {
                    var polyGraphic = oneSeg.SegGraphics.OfType<PolygonalRoiSegGraphic>().First();
                    firstIPresentationImage = callback(polyGraphic.ImageSopInstanceUid, polyGraphic.ImageFrameNumber);
                }
            }
            var firstImageSopProvider = firstIPresentationImage as IImageSopProvider;
            if (firstImageSopProvider == null)
                return null;

            var sourceSop = firstImageSopProvider.ImageSop; // source of the common DICOM attributes
            var dicomFile = _sopInstanceFactory.CreateFile(sourceSop);

            // NOTE. These modules are initialized by the factory:
            // patient IE
            // - PatientModule
            // - ClinicalTrialSubjectModule
            // study IE
            // - GeneralStudyModule
            // - PatientStudyModule
            // - ClinicalTrialStudyModule
            // equipment IE
            // - GeneralEquipmentModule

            // Data values
            const int instanceNumber = 1;
            var contentDateTime = DateTime.Now;

            var segDocumentIod = new SegmentationDocumentIod(dicomFile.DataSet);

            // PatientModule
            var patientModule = segDocumentIod.PatientModuleIod;
            // patientModule.PatientBreedDescription = null; // bug in CC code
            patientModule.DicomAttributeProvider[DicomTags.PatientBreedDescription].SetEmptyValue();

            // GeneralEquipmentModule
            var generalEquipmentModuleIod = segDocumentIod.GeneralEquipmentModuleIod;
            generalEquipmentModuleIod.DeviceSerialNumber = EnvironmentUtilities.MachineIdentifier;

            // GeneralSeriesModule
            var srcGeneralSeriesModuleIod = new GeneralSeriesModuleIod(sourceSop.DataSource);
            var generalSeriesModuleIod = segDocumentIod.GeneralSeriesModuleIod;
            generalSeriesModuleIod.SeriesDescription = _segDocument.SeriesDescription;
            generalSeriesModuleIod.SeriesNumber = _segDocument.SeriesNumber;
            generalSeriesModuleIod.Modality = Modality.Seg;
            generalSeriesModuleIod.SeriesInstanceUid = DicomUid.GenerateUid().UID;
            generalSeriesModuleIod.Laterality = srcGeneralSeriesModuleIod.Laterality;
            generalSeriesModuleIod.SeriesDateTime = _segDocument.CreationDateTime;
            generalSeriesModuleIod.PerformingPhysiciansName = srcGeneralSeriesModuleIod.PerformingPhysiciansName;
            generalSeriesModuleIod.PerformingPhysicianIdentificationSequence = srcGeneralSeriesModuleIod.PerformingPhysicianIdentificationSequence;
            generalSeriesModuleIod.ProtocolName = srcGeneralSeriesModuleIod.ProtocolName;
            {
                // General Description Code Sequence is missing from the GeneralSeriesModuleIod implementation
                var seriesDescriptionCodeSequence = new CodeSequenceMacro
                    {
                        CodeValue = "113076",
                        CodeMeaning = "Segmentation",
                        CodingSchemeDesignator = "DCM"
                    };
                var result = new[] { seriesDescriptionCodeSequence.DicomSequenceItem };

                generalSeriesModuleIod.DicomAttributeProvider[DicomTags.SeriesDescriptionCodeSequence].Values = result;
            }
            string userDicomName = null;
            if (_segDocument.UserInfo != null && !string.IsNullOrEmpty(_segDocument.UserInfo.Name))
            {
                userDicomName = FormatDicomName(_segDocument.UserInfo.Name);
                if (userDicomName != null)
                    generalSeriesModuleIod.OperatorsName = userDicomName;

                // NOTE: Login name is being ignored for now
            }
            generalSeriesModuleIod.BodyPartExamined = srcGeneralSeriesModuleIod.BodyPartExamined;
            generalSeriesModuleIod.PatientPosition = srcGeneralSeriesModuleIod.PatientPosition;
            generalSeriesModuleIod.RequestAttributesSequence = srcGeneralSeriesModuleIod.RequestAttributesSequence;
            //generalSeriesModuleIod.AnatomicalOrientationType = srcGeneralSeriesModuleIod.AnatomicalOrientationType;  // Not needed

            // FrameOfReferenceModule
            var srcFrameOfReferenceModuleIod = new FrameOfReferenceModuleIod(sourceSop.DataSource);
            segDocumentIod.FrameOfReferenceModuleIod.FrameOfReferenceUid = srcFrameOfReferenceModuleIod.FrameOfReferenceUid;
            segDocumentIod.FrameOfReferenceModuleIod.PositionReferenceIndicator = srcFrameOfReferenceModuleIod.PositionReferenceIndicator;

            // Initialize Segmentation Image Module first
            var segmentationImageModuleIod = segDocumentIod.SegmentationImageModuleIod;
            segmentationImageModuleIod.InitializeAttributes();

            // General Image Module and Segmentation Image Module
            var srcGeneralImageModuleIod = new GeneralImageModuleIod(sourceSop.DataSource);
            var generalImageModuleIod = segDocumentIod.GeneralImageModuleIod;
            generalImageModuleIod.InstanceNumber = instanceNumber;
            generalImageModuleIod.PatientOrientation = srcGeneralImageModuleIod.PatientOrientation;
            generalImageModuleIod.ContentDateTime = contentDateTime;
            generalImageModuleIod.ImageType = "DERIVED\\PRIMARY";
            generalImageModuleIod.AcquisitionNumber = srcGeneralImageModuleIod.AcquisitionNumber;
            generalImageModuleIod.AcquisitionDateTime = srcGeneralImageModuleIod.AcquisitionDateTime;
            generalImageModuleIod.QualityControlImage = srcGeneralImageModuleIod.QualityControlImage;
            generalImageModuleIod.BurnedInAnnotation = srcGeneralImageModuleIod.BurnedInAnnotation;
            generalImageModuleIod.RecognizableVisualFeatures = srcGeneralImageModuleIod.RecognizableVisualFeatures;
            generalImageModuleIod.LossyImageCompression = srcGeneralImageModuleIod.LossyImageCompression.HasValue && srcGeneralImageModuleIod.LossyImageCompression.Value;
            generalImageModuleIod.LossyImageCompressionMethod = srcGeneralImageModuleIod.LossyImageCompressionMethod;
            generalImageModuleIod.LossyImageCompressionRatio = srcGeneralImageModuleIod.LossyImageCompressionRatio;
            generalImageModuleIod.IrradiationEventUid = srcGeneralImageModuleIod.IrradiationEventUid;

            // Image Pixel Module and Segmentation Image Module
            var srcImagePixelModule = new ImagePixelMacroIod(sourceSop.DataSource);
            var imagePixelModule = segDocumentIod.ImagePixelModuleIod;
            imagePixelModule.Rows = srcImagePixelModule.Rows; // same height as the the image
            imagePixelModule.Columns = srcImagePixelModule.Columns; // same width as the image
            //imagePixelModule.PixelAspectRatio = srcImagePixelModule.PixelAspectRatio; // same as the image

            // Continue initialization of non-default values for the Segmentation Image Module
            segmentationImageModuleIod.ContentLabel = SanitizeDicomCsValue(_segDocument.ContentLabel);
            if (!string.IsNullOrEmpty(userDicomName))
                segmentationImageModuleIod.ContentCreatorsName = userDicomName;
            segmentationImageModuleIod.SegmentationType = SegmentationType.BINARY;

            // Per segmentation and per frame item initialization
            var docHasOneFrame = _segDocument.Segs.Where(item => item != null && item.SegGraphics != null).Sum(seg => seg.SegGraphics.OfType<PolygonalRoiSegGraphic>().Count()) == 1;
            var docHasOneSeg = _segDocument.Segs.Count(item => item != null && item.SegGraphics != null && item.SegGraphics.OfType<PolygonalRoiSegGraphic>().Any()) == 1;
            var multiFrameDimensionsModuleIod = segDocumentIod.MultiFrameDimensionModuleIod;
            multiFrameDimensionsModuleIod.InitializeAttributes();
            var segmentSequenceItems = new List<SegmentSequence>();
            var dimensionIndexSequenceItems = new List<DimensionIndexSequenceItem>();
            var dimensionOrganizationSequenceItems = new List<DimensionOrganizationSequenceItem>();
            var multiFrameFunctionalGroupsModuleIod = segDocumentIod.MultiFrameFunctionalGroupsModuleIod;
            multiFrameFunctionalGroupsModuleIod.InitializeAttributes();
            var perFrameFunctionalGroupSequenceItems = new List<FunctionalGroupsSequenceItem>();
            var frameBytesList = new List<byte[]>(); // list of pixel data for each frame
            var seriesUidToSopClassUidToSopInstanceUid = new Dictionary<string, Dictionary<string, HashSet<string>>>();
            var segmentNumber = 0;
            foreach (var seg in _segDocument.Segs)
            {
                segmentNumber++;
                Debug.Assert(segmentNumber == 1, "We're only supposed to create one Segment per document for now");

                // Segment Sequence initialization
                var segmentSequenceItemIod = segmentationImageModuleIod.CreateSegmentSequence();
                segmentSequenceItemIod.SegmentNumber = segmentNumber;
                segmentSequenceItemIod.SegmentLabel = seg.Label;
                segmentSequenceItemIod.SegmentDescription = seg.Description;
                segmentSequenceItemIod.SegmentAlgorithmType = "MANUAL";

                #region Category, Type, Anatomic Region, Anatomic Region Modifier

                var selectedCategory = seg.SelectedCategory;
                if (selectedCategory != null)
                {
                    // Category
                    var segmentedPropertyCategoryCodeSequenceItem = segmentSequenceItemIod.CreateSegmentedPropertyCategoryCodeSequence();
                    segmentedPropertyCategoryCodeSequenceItem.CodeValue = selectedCategory.CodeValue;
                    segmentedPropertyCategoryCodeSequenceItem.CodeMeaning = selectedCategory.CodeMeaning;
                    segmentedPropertyCategoryCodeSequenceItem.CodingSchemeDesignator = selectedCategory.CodingSchemeDesignator;
                    //if (!string.IsNullOrEmpty(selectedCategory.CodingSchemeVersion))
                    //    segmentedPropertyCategoryCodeSequenceItem.CodingSchemeVersion = selectedCategory.CodingSchemeVersion;
                    segmentSequenceItemIod.SegmentedPropertyCategoryCodeSequence = new[] { segmentedPropertyCategoryCodeSequenceItem };

                    // Type
                    if (selectedCategory.SelectedType != null)
                    {
                        var segmentedPropertyTypeCodeSequenceItem = segmentSequenceItemIod.CreateSegmentedPropertyTypeCodeSequence();
                        segmentedPropertyTypeCodeSequenceItem.CodeValue = selectedCategory.SelectedType.CodeValue;
                        segmentedPropertyTypeCodeSequenceItem.CodeMeaning = selectedCategory.SelectedType.CodeMeaning;
                        segmentedPropertyTypeCodeSequenceItem.CodingSchemeDesignator = selectedCategory.SelectedType.CodingSchemeDesignator;
                        //if (!string.IsNullOrEmpty(selectedCategory.SelectedType.CodingSchemeVersion))
                        //    segmentedPropertyTypeCodeSequenceItem.CodingSchemeVersion = selectedCategory.SelectedType.CodingSchemeVersion;

                        // Type modifier
                        if (selectedCategory.SelectedType.SelectedTypeModifier != null)
                        {
                            var segmentedPropertyTypeModifierCodeSequenceItem = new CodeSequenceMacro();
                            segmentedPropertyTypeModifierCodeSequenceItem.CodeValue = selectedCategory.SelectedType.SelectedTypeModifier.CodeValue;
                            segmentedPropertyTypeModifierCodeSequenceItem.CodeMeaning = selectedCategory.SelectedType.SelectedTypeModifier.CodeMeaning;
                            segmentedPropertyTypeModifierCodeSequenceItem.CodingSchemeDesignator = selectedCategory.SelectedType.SelectedTypeModifier.CodingSchemeDesignator;
                            //if (!string.IsNullOrEmpty(selectedCategory.SelectedType.SelectedTypeModifier.CodingSchemeVersion))
                            //    segmentedPropertyTypeModifierCodeSequenceItem.CodingSchemeVersion = selectedCategory.SelectedType.SelectedTypeModifier.CodingSchemeVersion;

                            segmentedPropertyTypeCodeSequenceItem.SegmentedPropertyTypeModifierCodeSequence = new[] {segmentedPropertyTypeModifierCodeSequenceItem};
                        }
                        segmentSequenceItemIod.SegmentedPropertyTypeCodeSequence = new[] { segmentedPropertyTypeCodeSequenceItem };
                    }

                    // Anatomic Region
                    var selectedAnatomicRegion = selectedCategory.SelectedAnatomicRegion;
                    if (selectedAnatomicRegion != null)
                    {
                        var anatomicRegionSequenceItem = segmentSequenceItemIod.CreateAnatomicRegionSequence();
                        anatomicRegionSequenceItem.CodeValue = selectedAnatomicRegion.CodeValue;
                        anatomicRegionSequenceItem.CodeMeaning = selectedAnatomicRegion.CodeMeaning;
                        anatomicRegionSequenceItem.CodingSchemeDesignator = selectedAnatomicRegion.CodingSchemeDesignator;
                        //if (!string.IsNullOrEmpty(selectedAnatomicRegion.CodingSchemeVersion))
                        //    anatomicRegionSequenceItem.CodingSchemeVersion = selectedAnatomicRegion.CodingSchemeVersion;

                        // Anatomic region Modifier
                        if (selectedAnatomicRegion.SelectedAnatomicRegionModifier != null)
                        {
                            var anatomicRegionModifierSequenceItem = new CodeSequenceMacro();
                            anatomicRegionModifierSequenceItem.CodeValue = selectedAnatomicRegion.SelectedAnatomicRegionModifier.CodeValue;
                            anatomicRegionModifierSequenceItem.CodeMeaning = selectedAnatomicRegion.SelectedAnatomicRegionModifier.CodeMeaning;
                            anatomicRegionModifierSequenceItem.CodingSchemeDesignator = selectedAnatomicRegion.SelectedAnatomicRegionModifier.CodingSchemeDesignator;
                            //if (!string.IsNullOrEmpty(selectedAnatomicRegion.SelectedAnatomicRegionModifier.CodingSchemeVersion))
                            //    anatomicRegionModifierSequenceItem.CodingSchemeVersion = selectedAnatomicRegion.SelectedAnatomicRegionModifier.CodingSchemeVersion;

                            anatomicRegionSequenceItem.AnatomicRegionModifierSequence = new[] { anatomicRegionModifierSequenceItem };
                        }
                        segmentSequenceItemIod.AnatomicRegionSequence = new[] { anatomicRegionSequenceItem };
                    }
                }

                #endregion

                segmentSequenceItemIod.RecomendedDisplayCIELabValue = LabColorHelpers.RgbColorToCIELabColor(seg.Color);
                segmentSequenceItems.Add(segmentSequenceItemIod);

                // Dimension Organization Sequence item
                var dimensionOrganizationUid = DicomUid.GenerateUid().UID;
                var dimensionOrganizationSequenceItem = multiFrameDimensionsModuleIod.CreateDimensionOrganizationSequenceItem();
                dimensionOrganizationSequenceItem.DimensionOrganizationUid = dimensionOrganizationUid;
                dimensionOrganizationSequenceItems.Add(dimensionOrganizationSequenceItem);

                // Dimension Index Sequence items
                var dimensionIndexSequenceItem1 = multiFrameDimensionsModuleIod.CreateDimensionIndexSequenceItem();
                dimensionIndexSequenceItem1.DimensionIndexPointer = DicomTags.StackId;
                dimensionIndexSequenceItem1.FunctionalGroupPointer = DicomTags.FrameContentSequence;
                dimensionIndexSequenceItem1.DimensionOrganizationUid = dimensionOrganizationUid;
                dimensionIndexSequenceItem1.DimensionDescriptionLabel = "Stack ID";
                dimensionIndexSequenceItems.Add(dimensionIndexSequenceItem1);
                var dimensionIndexSequenceItem2 = multiFrameDimensionsModuleIod.CreateDimensionIndexSequenceItem();
                dimensionIndexSequenceItem2.DimensionIndexPointer = DicomTags.InStackPositionNumber;
                dimensionIndexSequenceItem2.FunctionalGroupPointer = DicomTags.FrameContentSequence;
                dimensionIndexSequenceItem2.DimensionOrganizationUid = dimensionOrganizationUid;
                dimensionIndexSequenceItem2.DimensionDescriptionLabel = "In Stack Position Number";
                dimensionIndexSequenceItems.Add(dimensionIndexSequenceItem2);

                var inStackPositionIndex = 0;

                var presentationImagePolygons = new Dictionary<IPresentationImage, List<PolygonalRoiSegGraphic>>();
                foreach (var polygonalSegGraphic in seg.SegGraphics.OfType<PolygonalRoiSegGraphic>())
                {
                    var poly = polygonalSegGraphic.PolygonalRoiGraphic.Roi as PolygonalRoi;
                    if (poly != null)
                    {
                        var currentPresentationImage = callback(polygonalSegGraphic.ImageSopInstanceUid, polygonalSegGraphic.ImageFrameNumber);
                        if (presentationImagePolygons.ContainsKey(currentPresentationImage))
                            presentationImagePolygons[currentPresentationImage].Add(polygonalSegGraphic);
                        else
                            presentationImagePolygons.Add(poly.PresentationImage, new List<PolygonalRoiSegGraphic> { polygonalSegGraphic });
                    }
                    else
                    {
                        Debug.Assert(false, "Encountered non-polygonal graphic during segmentation serialization");
                    }
                }

                foreach (var presentationImage in presentationImagePolygons.Keys)
                {
                    var currentImageSopProvider = presentationImage as IImageSopProvider;

                    if (presentationImage == null)
                    {
                        Debug.Assert(false, "Failed to get IImageSopProvider for the current Segmentation graphic");
                        continue;
                    }

                    Debug.Assert(presentationImagePolygons[presentationImage].FirstOrDefault().ImageFrameNumber ==
                        currentImageSopProvider.Frame.FrameNumber,
                                 "Stored frame number must match with the current SOP Instance's value");

                    #region PerFrameFunctionalGroupSequenceItem

                    // Initialize Per Frame Functional Groups here and groups
                    var perFrameFunctionalGroupSequenceItem = multiFrameFunctionalGroupsModuleIod.CreatePerFrameFunctionalGroupsSequence();

                    if (!docHasOneSeg)
                    {
                        // Pixel Measures Functional Group (per frame)
                        InitializePixelMeasureFunctionalGroup(perFrameFunctionalGroupSequenceItem, currentImageSopProvider.Frame);

                        // Initialize Segmentation Functional Group (per frame)
                        InitializeSegmentationFunctionalGroup(perFrameFunctionalGroupSequenceItem, segmentNumber);

                        // Plane Orientation (Patient) Functional Group
                        InitializePlaneOrientationPatientFunctionalGroup(perFrameFunctionalGroupSequenceItem, currentImageSopProvider.Frame.ImageOrientationPatient);
                    }
                    if (!docHasOneFrame)
                    {
                        // Plain Position Patient Functional Group (per frame)
                        InitializePlanePositionPatientFunctionalGroup(perFrameFunctionalGroupSequenceItem, currentImageSopProvider.Frame.ImagePositionPatient);

                        // Derivation Image Functional Group (per frame)
                        InitializeDerivationImageFunctionalGroup(perFrameFunctionalGroupSequenceItem, currentImageSopProvider.ImageSop, currentImageSopProvider.Frame.FrameNumber);
                    }
                    else
                    {
                        Debug.Assert(firstImageSopProvider.ImageSop.SeriesInstanceUid == currentImageSopProvider.Frame.SeriesInstanceUid &&
                                     firstImageSopProvider.ImageSop.SopInstanceUid == currentImageSopProvider.ImageSop.SopInstanceUid,
                                     "initial image reference and the single image reference must be the same");
                    }

                    // Initialize Frame Content Functional Group
                    InitializeFrameContentFunctionalGroup(perFrameFunctionalGroupSequenceItem, segmentNumber, ++inStackPositionIndex);

                    perFrameFunctionalGroupSequenceItems.Add(perFrameFunctionalGroupSequenceItem);

                    #endregion PerFrameFunctionalGroupSequenceItem

                    // Store referenced image info in a dictionary for later use
                    {
                        var currentSeriesInstanceUid = currentImageSopProvider.ImageSop.SeriesInstanceUid;
                        var currentSopClassUid = currentImageSopProvider.ImageSop.SopClassUid;
                        var currentSopInstanceUid = currentImageSopProvider.ImageSop.SopInstanceUid;
                        if (!seriesUidToSopClassUidToSopInstanceUid.ContainsKey(currentSeriesInstanceUid))
                            seriesUidToSopClassUidToSopInstanceUid.Add(currentSeriesInstanceUid, new Dictionary<string, HashSet<string>>());
                        var sopClassToSopInstanceDic = seriesUidToSopClassUidToSopInstanceUid[currentSeriesInstanceUid];
                        if (!sopClassToSopInstanceDic.ContainsKey(currentSopClassUid))
                            sopClassToSopInstanceDic.Add(currentSopClassUid, new HashSet<string>());
                        sopClassToSopInstanceDic[currentSopClassUid].Add(currentSopInstanceUid);
                    }

                    var polygons = new List<IList<PointF>>();

                    // Get frame's pixel data here
                    foreach (var polygonalSegGraphic in presentationImagePolygons[presentationImage])
                    {
                        var poly = polygonalSegGraphic.PolygonalRoiGraphic.Roi as PolygonalRoi;
                        if (poly != null)
                        {
                            polygons.Add(poly.Polygon.Vertices);
                        }
                        else
                        {
                            Debug.Assert(false, "Encountered non-polygonal graphic during segmentation serialization");
                        }
                    }

                    var grayscalePixelData = CreateFramePixelData(presentationImage, polygons);
                    frameBytesList.Add(grayscalePixelData.Raw);
                }
            }

            segmentationImageModuleIod.SegmentSequence = segmentSequenceItems.ToArray();

            // Per Frame Functional Groups module
            multiFrameFunctionalGroupsModuleIod.PerFrameFunctionalGroupsSequence = perFrameFunctionalGroupSequenceItems.ToArray();

            #region SharedFunctionalGroupSequence

            // Shared Functional Group Sequence Item
            var sharedFunctionalGroupSequenceItem = multiFrameFunctionalGroupsModuleIod.CreateSharedFunctionalGroupsSequence();

            if (docHasOneSeg)
            {
                Debug.Assert(segmentNumber == 1, "This is for a single segment only");

                // Pixel Measures Functional Group (shared)
                InitializePixelMeasureFunctionalGroup(sharedFunctionalGroupSequenceItem, firstImageSopProvider.Frame);

                // Initialize Segmentation Functional Group (shared)
                InitializeSegmentationFunctionalGroup(sharedFunctionalGroupSequenceItem, segmentNumber);

                // Plane Orientation (Patient) Functional Group
                InitializePlaneOrientationPatientFunctionalGroup(sharedFunctionalGroupSequenceItem, firstImageSopProvider.Frame.ImageOrientationPatient);
            }

            if (docHasOneFrame)
            {
                // Plain Position Patient Functional Group
                InitializePlanePositionPatientFunctionalGroup(sharedFunctionalGroupSequenceItem, firstImageSopProvider.Frame.ImagePositionPatient);

                // Derivation Image Functional Group
                InitializeDerivationImageFunctionalGroup(sharedFunctionalGroupSequenceItem, firstImageSopProvider.ImageSop, firstImageSopProvider.Frame.FrameNumber);
            }

            multiFrameFunctionalGroupsModuleIod.SharedFunctionalGroupsSequence = sharedFunctionalGroupSequenceItem;

            #endregion SharedFunctionalGroupSequence

            // Multi-frame Dimensions module
            multiFrameDimensionsModuleIod.DimensionIndexSequence = dimensionIndexSequenceItems.ToArray();
            multiFrameDimensionsModuleIod.DimensionOrganizationSequence = dimensionOrganizationSequenceItems.ToArray();
            multiFrameDimensionsModuleIod.DimensionOrganizationType = "3D";

            // Multi-frame Functional Groups module
            multiFrameFunctionalGroupsModuleIod.SharedFunctionalGroupsSequence = sharedFunctionalGroupSequenceItem;
            multiFrameFunctionalGroupsModuleIod.PerFrameFunctionalGroupsSequence = perFrameFunctionalGroupSequenceItems.ToArray();
            multiFrameFunctionalGroupsModuleIod.NumberOfFrames = perFrameFunctionalGroupSequenceItems.Count;

            // Specimen Module
            var srcSpecimenModuleIod = new SpecimenModuleIod(sourceSop.DataSource);
            var specimenModuleIod = segDocumentIod.SpecimenModuleIod;
            //specimenModuleIod.ContainerIdentifier = srcSpecimenModuleIod.ContainerIdentifier;
            specimenModuleIod.IssuerOfTheContainterIdentifier = srcSpecimenModuleIod.IssuerOfTheContainterIdentifier;
            specimenModuleIod.AlternateContainerIdentifierSequence = srcSpecimenModuleIod.AlternateContainerIdentifierSequence;
            specimenModuleIod.ContainerTypeCodeSequence = srcSpecimenModuleIod.ContainerTypeCodeSequence;
            //specimenModuleIod.ContainerDescription = srcSpecimenModuleIod.ContainerDescription;
            specimenModuleIod.ContainerComponentSequence = srcSpecimenModuleIod.ContainerComponentSequence;
            specimenModuleIod.SpecimenDescriptionSequence = srcSpecimenModuleIod.SpecimenDescriptionSequence;

            // Common Instance Reference Module
            var referencedSeriesSequenceItems = new List<ReferencedSeriesSequenceIod>();
            foreach (
                var seriesToSopClassToSopInstanceDic in
                    seriesUidToSopClassUidToSopInstanceUid.Where(seriesToSopClassToSopInstanceDic => seriesToSopClassToSopInstanceDic.Value != null))
            {
                var referencedSopInstances = new List<ReferencedInstanceSequenceIod>();
                foreach (var sopClassToSopInstanceDic in seriesToSopClassToSopInstanceDic.Value.Where(sopClassToSopInstanceDic => sopClassToSopInstanceDic.Value != null))
                {
                    referencedSopInstances.AddRange(sopClassToSopInstanceDic.Value.Select(sopInstanceUid => new ReferencedInstanceSequenceIod
                        {
                            ReferencedSopClassUid = sopClassToSopInstanceDic.Key,
                            ReferencedSopInstanceUid = sopInstanceUid
                        }));
                }
                if (referencedSopInstances.Count > 0)
                {
                    referencedSeriesSequenceItems.Add(new ReferencedSeriesSequenceIod
                        {
                            SeriesInstanceUid = seriesToSopClassToSopInstanceDic.Key,
                            ReferencedInstanceSequence = referencedSopInstances.ToArray()
                        });
                }
            }
            if (referencedSeriesSequenceItems.Count > 0)
            {
                var commonInstanceReferenceModuleIod = segDocumentIod.CommonInstanceReferenceModuleIod;
                commonInstanceReferenceModuleIod.InitializeAttributes();
                commonInstanceReferenceModuleIod.ReferencedSeriesSequence = referencedSeriesSequenceItems.ToArray();
            }

            // SOP Common Module
            var srcSopCommonModuleIod = new SopCommonModuleIod(sourceSop.DataSource);
            var sopCommonModuleIod = segDocumentIod.SopCommonModuleIod;
            sopCommonModuleIod.SopClass = SopClass.SegmentationStorage;
            sopCommonModuleIod.SopInstanceUid = DicomUid.GenerateUid().UID;
            //sopCommonModuleIod.SpecificCharacterSet = "UTF-8"; // TBD -it's ISO_IR 192 by default
            sopCommonModuleIod.InstanceCreationDateTime = contentDateTime;
            sopCommonModuleIod.InstanceCreatorUid = InstanceCreatorUid;
            sopCommonModuleIod.TimezoneOffsetFromUtc = contentDateTime.ToString("zzz", DateTimeFormatInfo.InvariantInfo);
            //sopCommonModuleIod.LongitudinalTemporalInformationModified = srcSopCommonModuleIod.LongitudinalTemporalInformationModified; // has a bug in CC

            // Pixel data
            {
                Debug.Assert(frameBytesList.TrueForAll(bytes => bytes.Length == frameBytesList[0].Length), "Allocated buffers for all frames must be of the same size");
                var byteBuffer = new byte[frameBytesList[0].Length * frameBytesList.Count];
                using (var stream = new MemoryStream(byteBuffer))
                {
                    foreach (var frameBytes in frameBytesList)
                        stream.Write(frameBytes, 0, frameBytes.Length);
                }
                // Byte Packing
                // TODO FIXME: we can do in-place byte packing without allocating the second array!
                var packetBuffer = new byte[(int) Math.Ceiling(byteBuffer.Length/8.0)];
                var numberOfFullBytes = byteBuffer.Length/8;
                for (var i = 0; i < numberOfFullBytes; i++)
                {
                    var newByte = packetBuffer[i];
                    for (var y = 0; y < 8; y++)
                    {
                        var bitMask = (byte) (1 << y);
                        newByte = (byte) ((byteBuffer[8*i + y] & 0xFF) > 0 ? newByte | bitMask : newByte & ~bitMask);
                    }
                    packetBuffer[i] = newByte;
                }
                // last byte(s) TODO VK: handle padding for non-even number of bytes. make sure padded bits are initialized to 0
                if (numberOfFullBytes < packetBuffer.Length)
                {
                    // Pack leftover bytes ( < 8)
                    Debug.Assert(packetBuffer.Length - numberOfFullBytes == 1, "Wrong destination bytes count during packing");
                    Debug.Assert(byteBuffer.Length - numberOfFullBytes*8 < 8, "Wrong leftover bytes count during packing");
                    var newByte = packetBuffer[packetBuffer.Length - 1];
                    for (var y = numberOfFullBytes * 8; y < byteBuffer.Length; y++)
                    {
                        var bitMask = (byte) (1 << (y%8));
                        newByte = (byte) ((byteBuffer[y] & 0xFF) > 0 ? newByte | bitMask : newByte & ~bitMask);
                    }
                    packetBuffer[packetBuffer.Length - 1] = newByte;
                }
                var pdAttribute = new DicomAttributeOW(DicomTags.PixelData);
                using (var stream = pdAttribute.AsStream())
                {
                    stream.Write(packetBuffer, 0, packetBuffer.Length);
                }

                multiFrameFunctionalGroupsModuleIod.DicomAttributeProvider[DicomTags.PixelData] = pdAttribute;
            }

            dicomFile.MediaStorageSopClassUid = SopClass.SegmentationStorageUid;
            dicomFile.MediaStorageSopInstanceUid = segDocumentIod.SopInstanceUid;

            // Update the original document with new values
            _segDocument.SeriesInstanceUid = segDocumentIod.SeriesInstanceUid;
            _segDocument.SopInstanceUid = segDocumentIod.SopInstanceUid;

            return dicomFile;
        }
			/// <summary>
			/// Initializes the frame data container from an OW Pixel Data attribute.
			/// </summary>
			public FrameDataOW(DicomUncompressedPixelData owner, DicomAttributeOW pixelDataAttribute, int frameIndex)
				: base(owner)
			{
				_owAttrib = pixelDataAttribute;
				_frameIndex = frameIndex;
			}
Example #5
0
       public static bool Convert2Dicom(byte[] pixelData, string rawFileName, DataRow patientInfo, bool delbeforeSave, string AutoWLPath)
        {
            try
            {
                const string colPid = "PID";
                const string colKVP = "KVP";
                const string colMAS = "MAS";
                const string colDepartmentName = "Department_Name";
                const string colPatientName = "Patient_Name";
                const string colPatientSex = "Patient_Sex";
                const string colPatientAge = "Patient_Age";
                const string colPatientBirthdate = "Patient_Birthdate";
                const string colRegDate = "Reg_Date";
                const string colRegNum = "Reg_Num";
                const string colImgWidth = "IMGWidth";
                const string colImgHeight = "IMGHeigh";
                const string colModalityCode = "Modality_Code";
                const string colAtonomyCode = "Atonomy_Code";
                const string colProjectionCode = "Projection_Code";
                const string colHostpitalName = "Hostpital_Name";
                const string colMonoChrome = "MonoChrome";

                const string _colStudyInstanceUID = "StudyInstanceUID";
                const string colSeriesInstanceUID = "SeriesInstanceUID";
                const string colSOPInstanceUID = "SOPInstanceUID";
                const string colAcqDate = "AcqDate";
                const string colAppName = "AppName";

                const string colBitsStored = "BitsStored";
                const string colHightBit = "HightBit";
                const string colBitsAllocated = "BitsAllocated";

                _bitsStored = TryGetBitsStored(patientInfo, colBitsStored);
                var _HightBit = TryGetBitsStored(patientInfo, colHightBit);
                var _BitsAllocated = TryGetBitsStored(patientInfo, colBitsAllocated);

                var MonoChrome = TryGetString(patientInfo, colMonoChrome, "MONOCHROME2");
                
                var pid = TryGetString(patientInfo, colPid);
                var _KVP = TryGetString(patientInfo, colKVP);
                var _MAS = TryGetString(patientInfo, colMAS);
                var patientName = TryGetString(patientInfo, colPatientName);
                var patientSex = TryGetString(patientInfo, colPatientSex);
                var patientAge = TryGetString(patientInfo, colPatientAge);
                var patientBirthdate = TryGetString(patientInfo, colPatientBirthdate);
                var regDate = TryGetString(patientInfo, colRegDate);
                var regNum = TryGetString(patientInfo, colRegNum);
                var imgWidth = TryGetString(patientInfo, colImgWidth);
                var imgHeigh = TryGetString(patientInfo, colImgHeight);
                var modalityCode = TryGetString(patientInfo, colModalityCode);
                var atonomyCode = TryGetString(patientInfo, colAtonomyCode);
                var projectionCode = TryGetString(patientInfo, colProjectionCode);
                var hostpitalName = TryGetString(patientInfo, colHostpitalName, "BACH MAI HOSTPITAL");
                var departmentName = TryGetString(patientInfo, colDepartmentName, "Khoa chan doan hinh anh");
                string defaultStudyInstanceUID = ClearCanvas.Dicom.DicomUid.GenerateUid().UID;
                string defaultSeriesInstanceUID = defaultStudyInstanceUID + ".1";
                string defaultSOPInstanceUID = defaultSeriesInstanceUID + ".1";
                var StudyInstanceUID = TryGetString(patientInfo, _colStudyInstanceUID, defaultStudyInstanceUID);
                var SeriesInstanceUID = TryGetString(patientInfo, colSeriesInstanceUID, defaultSeriesInstanceUID);
                var SOPInstanceUID = TryGetString(patientInfo, colSOPInstanceUID, defaultSOPInstanceUID);
                var AppName = TryGetString(patientInfo, colAppName, "VBIT");
                string dicomPath = Path.GetDirectoryName(rawFileName);

                // Lấy về tên file Dicom từ file raw
                string dicomFileName = string.Format("{0}{1}{2}.DCM", dicomPath, Path.DirectorySeparatorChar,
                                                     Path.GetFileNameWithoutExtension(rawFileName));

                if (delbeforeSave && File.Exists(dicomFileName)) Try2DelFile(dicomFileName);
                else
                    try2RenameExistedFile(dicomFileName);
                


                //FileStream fs = File.OpenRead(rawFileName);

                //long length = fs.Length;
                long dataLength = pixelData.Length;

                string col = imgWidth.ToString();
                string row = imgHeigh.ToString();
                // GetSize(dataLength, out col, out row);

                // Tạo File Dicom để lưu thông tin
                var dcmFile = new DicomFile(dicomFileName);
                DicomAttributeCollection dicomDataSet = dcmFile.DataSet;

                //Set Tag For File
                DateTime studyTime = DateTime.Now;
                dicomDataSet[DicomTags.SpecificCharacterSet].SetStringValue("ISO_IR 100");
                dicomDataSet[DicomTags.ImageType].SetStringValue("ORIGINAL\\PRIMARY\\OTHER\\M\\FFE");
                dicomDataSet[DicomTags.InstanceCreationDate].SetStringValue(DateParser.ToDicomString(studyTime));
                dicomDataSet[DicomTags.InstanceCreationTime].SetStringValue(TimeParser.ToDicomString(studyTime));
                dicomDataSet[DicomTags.SopClassUid].SetStringValue(SopClass.MrImageStorageUid);
                dicomDataSet[DicomTags.SopInstanceUid].SetStringValue(SOPInstanceUID);
                dicomDataSet[DicomTags.StudyDate].SetStringValue(regDate);
                dicomDataSet[DicomTags.ApplicationName].SetStringValue(AppName);
                dicomDataSet[DicomTags.StudyTime].SetStringValue(TimeParser.ToDicomString(studyTime));
                dicomDataSet[DicomTags.SeriesDate].SetStringValue(regDate);
                dicomDataSet[DicomTags.SeriesTime].SetStringValue(TimeParser.ToDicomString(studyTime));
                dicomDataSet[DicomTags.AccessionNumber].SetStringValue(regNum);
                dicomDataSet[DicomTags.Modality].SetStringValue(modalityCode);
                dicomDataSet[DicomTags.Manufacturer].SetStringValue("VBIT");
                dicomDataSet[DicomTags.StationName].SetStringValue(AppName);
                dicomDataSet[DicomTags.ExposureInMas].SetStringValue(_MAS);
                dicomDataSet[DicomTags.Kvp].SetStringValue(_KVP);
                dicomDataSet[DicomTags.ManufacturersModelName].SetNullValue();
                dicomDataSet[DicomTags.InstitutionName].SetStringValue(hostpitalName);
                dicomDataSet[DicomTags.InstitutionalDepartmentName].SetStringValue(departmentName);
                //dicomDataSet[DicomTags.StudyDescription].SetStringValue("HEART");
                //dicomDataSet[DicomTags.SeriesDescription].SetStringValue("Heart 2D EPI BH TRA");
                //dicomDataSet[DicomTags.PatientsName].SetStringValue("Patient^Test");
                dicomDataSet[DicomTags.PatientsName].SetStringValue(patientName);
                dicomDataSet[DicomTags.PatientId].SetStringValue(pid);
                dicomDataSet[DicomTags.PatientsBirthDate].SetStringValue(patientBirthdate);
                dicomDataSet[DicomTags.PatientsSex].SetStringValue(patientSex);
                dicomDataSet[DicomTags.PatientsAge].SetStringValue(patientAge);
                dicomDataSet[DicomTags.PatientsWeight].SetStringValue("70");
                dicomDataSet[DicomTags.SequenceVariant].SetStringValue("OTHER");
                dicomDataSet[DicomTags.ScanOptions].SetStringValue("CG");
                dicomDataSet[DicomTags.MrAcquisitionType].SetStringValue("2D");
                dicomDataSet[DicomTags.SliceThickness].SetStringValue("2");
                dicomDataSet[DicomTags.RepetitionTime].SetStringValue("857.142883");
                dicomDataSet[DicomTags.EchoTime].SetStringValue("8.712100");
                dicomDataSet[DicomTags.NumberOfAverages].SetStringValue("1");
                dicomDataSet[DicomTags.ImagingFrequency].SetStringValue("63.901150");
                dicomDataSet[DicomTags.ImagedNucleus].SetStringValue("1H");
                dicomDataSet[DicomTags.EchoNumbers].SetStringValue("1");
                dicomDataSet[DicomTags.MagneticFieldStrength].SetStringValue("1.500000");
                dicomDataSet[DicomTags.SpacingBetweenSlices].SetStringValue("10.00000");
                dicomDataSet[DicomTags.NumberOfPhaseEncodingSteps].SetStringValue("81");
                dicomDataSet[DicomTags.EchoTrainLength].SetStringValue("0");
                dicomDataSet[DicomTags.PercentSampling].SetStringValue("63.281250");
                dicomDataSet[DicomTags.PercentPhaseFieldOfView].SetStringValue("68.75000");
                dicomDataSet[DicomTags.DeviceSerialNumber].SetStringValue("1234");
                dicomDataSet[DicomTags.SoftwareVersions].SetStringValue("V1.0");
                dicomDataSet[DicomTags.ProtocolName].SetStringValue("2D EPI BH");
                dicomDataSet[DicomTags.TriggerTime].SetStringValue("14.000000");
                dicomDataSet[DicomTags.LowRRValue].SetStringValue("948");
                dicomDataSet[DicomTags.HighRRValue].SetStringValue("1178");
                dicomDataSet[DicomTags.IntervalsAcquired].SetStringValue("102");
                dicomDataSet[DicomTags.IntervalsRejected].SetStringValue("0");
                dicomDataSet[DicomTags.HeartRate].SetStringValue("56");
                dicomDataSet[DicomTags.ReceiveCoilName].SetStringValue("B");
                dicomDataSet[DicomTags.TransmitCoilName].SetStringValue("B");
                dicomDataSet[DicomTags.InPlanePhaseEncodingDirection].SetStringValue("COL");
                dicomDataSet[DicomTags.FlipAngle].SetStringValue("50.000000");
                dicomDataSet[DicomTags.PatientPosition].SetStringValue("HFS");
                dicomDataSet[DicomTags.StudyInstanceUid].SetStringValue(StudyInstanceUID);
                dicomDataSet[DicomTags.SeriesInstanceUid].SetStringValue(SeriesInstanceUID);
                //dicomDataSet[DicomTags.StudyId].SetStringValue(pid);
                dicomDataSet[DicomTags.SeriesNumber].SetStringValue("1");
                dicomDataSet[DicomTags.AcquisitionNumber].SetStringValue("7");
                dicomDataSet[DicomTags.InstanceNumber].SetStringValue("1");
                dicomDataSet[DicomTags.ImagePositionPatient].SetStringValue("-61.7564\\-212.04848\\-99.6208");
                dicomDataSet[DicomTags.ImageOrientationPatient].SetStringValue("0.861\\0.492\\0.126\\-0.2965");
                dicomDataSet[DicomTags.FrameOfReferenceUid].SetStringValue(DicomUid.GenerateUid().UID);
                dicomDataSet[DicomTags.PositionReferenceIndicator].SetStringValue(null);
                //dicomDataSet[DicomTags.ImageComments].SetStringValue("Test MR Image");
                dicomDataSet[DicomTags.SamplesPerPixel].SetStringValue("1");
                dicomDataSet[DicomTags.PhotometricInterpretation].SetStringValue(MonoChrome);
                dicomDataSet[DicomTags.Rows].SetStringValue(row);
                dicomDataSet[DicomTags.Columns].SetStringValue(col);

                dicomDataSet[DicomTags.PixelSpacing].SetStringValue("0.168\\0.168");
                dicomDataSet[DicomTags.BitsAllocated].SetStringValue(_BitsAllocated.ToString());
                dicomDataSet[DicomTags.BitsStored].SetStringValue(_bitsStored.ToString());
                dicomDataSet[DicomTags.HighBit].SetStringValue(_HightBit.ToString());
                dicomDataSet[DicomTags.PixelRepresentation].SetStringValue("0");

                if (File.Exists(AutoWLPath))
                {
                    switch (_bitsStored)
                    {
                        case 12:
                            dicomDataSet[DicomTags.WindowCenter].SetStringValue("2048");
                            dicomDataSet[DicomTags.WindowWidth].SetStringValue("4095");

                            break;

                        case 14:
                            dicomDataSet[DicomTags.WindowCenter].SetStringValue("8192");
                            dicomDataSet[DicomTags.WindowWidth].SetStringValue("16383");

                            break;

                        case 16:
                            dicomDataSet[DicomTags.WindowCenter].SetStringValue("32767");
                            dicomDataSet[DicomTags.WindowWidth].SetStringValue("65535");
                            break;

                        default:
                            dicomDataSet[DicomTags.WindowCenter].SetStringValue("32767");
                            dicomDataSet[DicomTags.WindowWidth].SetStringValue("65535");
                            break;
                    }

                }

                //dicomDataSet[DicomTags.SmallestImagePixelValue].SetStringValue("32772");
                //dicomDataSet[DicomTags.LargestImagePixelValue].SetStringValue("47745");
                dicomDataSet[DicomTags.RescaleIntercept].SetStringValue("0.");
                dicomDataSet[DicomTags.RescaleSlope].SetStringValue("1.");


                dicomDataSet[DicomTags.ViewPosition].SetStringValue(projectionCode);
                dicomDataSet[DicomTags.BodyPartExamined].SetStringValue(atonomyCode);


                //Gán Dữ liệu ảnh
                var pixels = new DicomAttributeOW(DicomTags.PixelData) { Values = pixelData };
                dicomDataSet[DicomTags.PixelData] = pixels;

                var item = new DicomSequenceItem();
                dicomDataSet[DicomTags.RequestAttributesSequence].AddSequenceItem(item);
                item[DicomTags.RequestedProcedureId].SetStringValue("MRR1234");
                item[DicomTags.ScheduledProcedureStepId].SetStringValue("MRS1234");

                item = new DicomSequenceItem();
                dicomDataSet[DicomTags.RequestAttributesSequence].AddSequenceItem(item);

                item[DicomTags.RequestedProcedureId].SetStringValue("MR2R1234");
                item[DicomTags.ScheduledProcedureStepId].SetStringValue("MR2S1234");

                var studyItem = new DicomSequenceItem();

                item[DicomTags.ReferencedStudySequence].AddSequenceItem(studyItem);

                studyItem[DicomTags.ReferencedSopClassUid].SetStringValue(SopClass.MrImageStorageUid);
                studyItem[DicomTags.ReferencedSopInstanceUid].SetStringValue("1.2.3.4.5.6.7.8.9");

                //Set Meta Info
                dicomDataSet[DicomTags.MediaStorageSopClassUid].SetStringValue(
                    dcmFile.DataSet[DicomTags.SopClassUid].GetString(0, ""));
                dicomDataSet[DicomTags.MediaStorageSopInstanceUid].SetStringValue(
                    dcmFile.DataSet[DicomTags.SopInstanceUid].GetString(0, ""));

                dcmFile.TransferSyntax = TransferSyntax.ExplicitVrLittleEndian;

                dicomDataSet[DicomTags.ImplementationClassUid].SetStringValue("1.1.1.1.1.11.1");
                dicomDataSet[DicomTags.ImplementationVersionName].SetStringValue("droc 1.0");

                // Lưu File
                dcmFile.Save();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
Example #6
0
        public void SetupMultiframeXA(DicomAttributeCollection theSet, uint rows, uint columns, uint frames)
        {
			DateTime studyTime = DateTime.Now;
			theSet[DicomTags.SpecificCharacterSet].SetStringValue("ISO_IR 100");
            theSet[DicomTags.ImageType].SetStringValue("DERIVED\\SECONDARY\\SINGLE PLANE\\SINGLE A");
			theSet[DicomTags.InstanceCreationDate].SetStringValue(DateParser.ToDicomString(DateTime.Now));
			theSet[DicomTags.InstanceCreationTime].SetStringValue(TimeParser.ToDicomString(DateTime.Now));
			theSet[DicomTags.SopClassUid].SetStringValue(SopClass.XRayAngiographicImageStorageUid);
            theSet[DicomTags.SopInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
			theSet[DicomTags.StudyDate].SetStringValue(DateParser.ToDicomString(studyTime));
			theSet[DicomTags.StudyTime].SetStringValue(TimeParser.ToDicomString(studyTime));
			theSet[DicomTags.SeriesDate].SetStringValue(DateParser.ToDicomString(studyTime));
			theSet[DicomTags.SeriesTime].SetStringValue(TimeParser.ToDicomString(studyTime));
			theSet[DicomTags.AccessionNumber].SetStringValue("A4567");
            theSet[DicomTags.Modality].SetStringValue("XA");
            theSet[DicomTags.Manufacturer].SetStringValue("ClearCanvas");
            theSet[DicomTags.InstitutionName].SetStringValue("KardiologieUniklinikHeidelberg");
            theSet[DicomTags.ReferringPhysiciansName].SetStringValue("Last^First");
            theSet[DicomTags.StudyDescription].SetStringValue("HEART");
            theSet[DicomTags.SeriesDescription].SetStringValue("Heart 2D EPI BH TRA");
            theSet[DicomTags.PatientsName].SetStringValue("Patient^Test");
            theSet[DicomTags.PatientId].SetStringValue("ID123-45-9999");
            theSet[DicomTags.PatientsBirthDate].SetStringValue("19600101");
            theSet[DicomTags.PatientsSex].SetStringValue("M");
            theSet[DicomTags.PatientsWeight].SetStringValue("80");
            theSet[DicomTags.PatientsSize].SetStringValue("10.000244140625");
            theSet[DicomTags.Kvp].SetStringValue("80");
            theSet[DicomTags.ProtocolName].SetStringValue("25  FPS Koronarien");
            theSet[DicomTags.FrameTime].SetStringValue("40");
            theSet[DicomTags.FrameDelay].SetStringValue("0");
            theSet[DicomTags.DistanceSourceToDetector].SetStringValue("1018");
            theSet[DicomTags.ExposureTime].SetStringValue("7");
            theSet[DicomTags.XRayTubeCurrent].SetStringValue("815");
            theSet[DicomTags.RadiationSetting].SetStringValue("GR");
            theSet[DicomTags.IntensifierSize].SetStringValue("169.99998");
            theSet[DicomTags.PositionerMotion].SetStringValue("STATIC");
            theSet[DicomTags.PositionerPrimaryAngle].SetStringValue("-40.2999999");
            theSet[DicomTags.PositionerSecondaryAngle].SetStringValue("-15.5");
            theSet[DicomTags.DeviceSerialNumber].SetStringValue("1234");
            theSet[DicomTags.SoftwareVersions].SetStringValue("V1.0");
            theSet[DicomTags.StudyInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
            theSet[DicomTags.SeriesInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
            theSet[DicomTags.StudyId].SetStringValue("20021208125233");
            theSet[DicomTags.SeriesNumber].SetStringValue("1");
            theSet[DicomTags.AcquisitionNumber].SetStringValue("3");
            theSet[DicomTags.InstanceNumber].SetStringValue("13");
            theSet[DicomTags.PatientOrientation].SetNullValue();
            theSet[DicomTags.ImagesInAcquisition].SetStringValue("1");
            theSet[DicomTags.SamplesPerPixel].SetStringValue("1");
            theSet[DicomTags.PhotometricInterpretation].SetStringValue("MONOCHROME2");
            theSet[DicomTags.NumberOfFrames].SetUInt32(0, frames);
            theSet[DicomTags.Rows].SetUInt32(0,rows);
            theSet[DicomTags.Columns].SetUInt32(0, columns);
            theSet[DicomTags.FrameIncrementPointer].SetUInt32(0,DicomTags.FrameTime);
            theSet[DicomTags.BitsAllocated].SetStringValue("8");
            theSet[DicomTags.BitsStored].SetStringValue("8");
            theSet[DicomTags.HighBit].SetStringValue("7");
            theSet[DicomTags.PixelRepresentation].SetStringValue("0");
            theSet[DicomTags.WindowCenter].SetStringValue("128");
            theSet[DicomTags.WindowWidth].SetStringValue("204.8");
            theSet[DicomTags.PerformedProcedureStepStartDate].SetStringValue("20080219");
            theSet[DicomTags.PerformedProcedureStepStartTime].SetStringValue("143600");
            theSet[DicomTags.PerformedProcedureStepId].SetStringValue("UNKNOWN");

			// Null SQ Test
			theSet[DicomTags.ReferencedStudySequence].SetNullValue();

			// FL & FD tags for testing
			theSet[DicomTags.SlabThickness].SetFloat64(0,0.1234567d);
			theSet[DicomTags.CalciumScoringMassFactorPatient].SetFloat32(0, 0.7654321f);

            uint length = rows * columns * frames;
            if (length % 2 == 1)
                length++;
            DicomAttributeOW pixels = new DicomAttributeOW(DicomTags.PixelData);

            byte[] pixelArray = new byte[length];
            pixelArray[length - 1] = 0x00; // Padding char

            for (uint frameCount = 0; frameCount < frames; frameCount++)
                for (uint i = frameCount * rows * columns, val = frameCount + 1; i < (frameCount + 1) * rows * columns; i++, val++)
                    pixelArray[i] = (byte)(val % 255);
            
            pixels.Values = pixelArray;

            theSet[DicomTags.PixelData] = pixels;

            DicomSequenceItem item = new DicomSequenceItem();
            theSet[DicomTags.RequestAttributesSequence].AddSequenceItem(item);

            item[DicomTags.RequestedProcedureId].SetStringValue("XA123");
            item[DicomTags.ScheduledProcedureStepId].SetStringValue("XA1234");

            item = new DicomSequenceItem();
            theSet[DicomTags.RequestAttributesSequence].AddSequenceItem(item);

            item[DicomTags.RequestedProcedureId].SetStringValue("XA123");
            item[DicomTags.ScheduledProcedureStepId].SetStringValue("XA1234");


        }
Example #7
0
		public void SetupSecondaryCapture(DicomAttributeCollection theSet)
		{
			DateTime studyTime = DateTime.Now;
			theSet[DicomTags.SpecificCharacterSet].SetStringValue("ISO_IR 100");
			theSet[DicomTags.ImageType].SetStringValue("ORIGINAL\\PRIMARY\\OTHER\\");
			theSet[DicomTags.InstanceCreationDate].SetStringValue(DateParser.ToDicomString(DateTime.Now));
			theSet[DicomTags.InstanceCreationTime].SetStringValue(TimeParser.ToDicomString(DateTime.Now));
			theSet[DicomTags.SopClassUid].SetStringValue(SopClass.SecondaryCaptureImageStorageUid);
			theSet[DicomTags.SopInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
			theSet[DicomTags.StudyDate].SetStringValue(DateParser.ToDicomString(studyTime));
			theSet[DicomTags.StudyTime].SetStringValue(TimeParser.ToDicomString(studyTime));
			theSet[DicomTags.SeriesDate].SetStringValue(DateParser.ToDicomString(studyTime));
			theSet[DicomTags.SeriesTime].SetStringValue(TimeParser.ToDicomString(studyTime));
			theSet[DicomTags.AccessionNumber].SetStringValue("A1234");
			theSet[DicomTags.Modality].SetStringValue("MR");
			theSet[DicomTags.Manufacturer].SetStringValue("ClearCanvas");
			theSet[DicomTags.ManufacturersModelName].SetNullValue();
			theSet[DicomTags.InstitutionName].SetStringValue("Toronto General Hospital");
			theSet[DicomTags.ReferringPhysiciansName].SetStringValue("Last^First");
			theSet[DicomTags.StudyDescription].SetStringValue("TEST");
			theSet[DicomTags.SeriesDescription].SetStringValue("TEST");
			theSet[DicomTags.PatientsName].SetStringValue("Patient^Test");
			theSet[DicomTags.PatientId].SetStringValue("ID123-45-9999");
			theSet[DicomTags.PatientsBirthDate].SetStringValue("19600102");
            theSet[DicomTags.PatientsSize].SetStringValue("10.000244140625");
            theSet[DicomTags.SequenceVariant].SetStringValue("OTHER");
			theSet[DicomTags.DeviceSerialNumber].SetStringValue("1234");
			theSet[DicomTags.SoftwareVersions].SetStringValue("V1.0");
			theSet[DicomTags.PatientPosition].SetStringValue("HFS");
			theSet[DicomTags.StudyInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
			theSet[DicomTags.SeriesInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
			theSet[DicomTags.StudyId].SetStringValue("1933");
			theSet[DicomTags.SeriesNumber].SetStringValue("1");
			theSet[DicomTags.InstanceNumber].SetStringValue("1");
			theSet[DicomTags.ImageComments].SetStringValue("Test SC Image");
			theSet[DicomTags.SamplesPerPixel].SetStringValue("1");
			theSet[DicomTags.PhotometricInterpretation].SetStringValue("MONOCHROME2");
			theSet[DicomTags.Rows].SetStringValue("256");
			theSet[DicomTags.Columns].SetStringValue("256");
			theSet[DicomTags.BitsAllocated].SetStringValue("16");
			theSet[DicomTags.BitsStored].SetStringValue("12");
			theSet[DicomTags.HighBit].SetStringValue("11");
			theSet[DicomTags.PixelRepresentation].SetStringValue("0");
            
			uint length = 256 * 256 * 2;

			DicomAttributeOW pixels = new DicomAttributeOW(DicomTags.PixelData);

			byte[] pixelArray = new byte[length];

			for (uint i = 0; i < length; i += 2)
				pixelArray[i] = (byte)(i % 255);

			pixels.Values = pixelArray;

			theSet[DicomTags.PixelData] = pixels;

			DicomSequenceItem item = new DicomSequenceItem();
			theSet[DicomTags.RequestAttributesSequence].AddSequenceItem(item);

			item[DicomTags.RequestedProcedureId].SetStringValue("MRR1234");
			item[DicomTags.ScheduledProcedureStepId].SetStringValue("MRS1234");

			item = new DicomSequenceItem();
			theSet[DicomTags.RequestAttributesSequence].AddSequenceItem(item);

			item[DicomTags.RequestedProcedureId].SetStringValue("MR2R1234");
			item[DicomTags.ScheduledProcedureStepId].SetStringValue("MR2S1234");

			DicomSequenceItem studyItem = new DicomSequenceItem();

			item[DicomTags.ReferencedStudySequence].AddSequenceItem(studyItem);

			studyItem[DicomTags.ReferencedSopClassUid].SetStringValue(SopClass.SecondaryCaptureImageStorageUid);
			studyItem[DicomTags.ReferencedSopInstanceUid].SetStringValue("1.2.3.4.5.6.7.8.9");

		}
Example #8
0
		public void SetupMR(DicomAttributeCollection theSet)
		{
			DateTime studyTime = DateTime.Now;
			theSet[DicomTags.SpecificCharacterSet].SetStringValue("ISO_IR 100");
			theSet[DicomTags.ImageType].SetStringValue("ORIGINAL\\PRIMARY\\OTHER\\M\\FFE");
			theSet[DicomTags.InstanceCreationDate].SetStringValue(DateParser.ToDicomString(DateTime.Now));
			theSet[DicomTags.InstanceCreationTime].SetStringValue(TimeParser.ToDicomString(DateTime.Now));
            theSet[DicomTags.AcquisitionDatetime].SetDateTime(0, DateTime.Now);
            theSet[DicomTags.SopClassUid].SetStringValue(SopClass.MrImageStorageUid);
			theSet[DicomTags.SopInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
			theSet[DicomTags.StudyDate].SetStringValue(DateParser.ToDicomString(studyTime));
			theSet[DicomTags.StudyTime].SetStringValue(TimeParser.ToDicomString(studyTime));
			theSet[DicomTags.SeriesDate].SetStringValue(DateParser.ToDicomString(studyTime));
			theSet[DicomTags.SeriesTime].SetStringValue(TimeParser.ToDicomString(studyTime));
			theSet[DicomTags.AccessionNumber].SetStringValue("A1234");
			theSet[DicomTags.Modality].SetStringValue("MR");
			theSet[DicomTags.Manufacturer].SetStringValue("ClearCanvas");
			theSet[DicomTags.ManufacturersModelName].SetNullValue();
			theSet[DicomTags.InstitutionName].SetStringValue("Mount Sinai Hospital");
			theSet[DicomTags.ReferringPhysiciansName].SetStringValue("Last^First");
			theSet[DicomTags.StudyDescription].SetStringValue("HEART");
			theSet[DicomTags.SeriesDescription].SetStringValue("Heart 2D EPI BH TRA");
			theSet[DicomTags.PatientsName].SetStringValue("Patient^Test");
			theSet[DicomTags.PatientId].SetStringValue("ID123-45-9999");
			theSet[DicomTags.PatientsBirthDate].SetStringValue("19600101");
			theSet[DicomTags.PatientsSex].SetStringValue("M");
			theSet[DicomTags.PatientsWeight].SetStringValue("70");
            theSet[DicomTags.PatientsSize].SetStringValue("10.000244140625");
            theSet[DicomTags.PatientsAge].SetStringValue("035Y");
            theSet[DicomTags.SequenceVariant].SetStringValue("OTHER");
			theSet[DicomTags.ScanOptions].SetStringValue("CG");
			theSet[DicomTags.MrAcquisitionType].SetStringValue("2D");
			theSet[DicomTags.SliceThickness].SetStringValue("10.000000");
			theSet[DicomTags.RepetitionTime].SetStringValue("857.142883");
			theSet[DicomTags.EchoTime].SetStringValue("8.712100");
			theSet[DicomTags.NumberOfAverages].SetStringValue("1");
			theSet[DicomTags.ImagingFrequency].SetStringValue("63.901150");
			theSet[DicomTags.ImagedNucleus].SetStringValue("1H");
			theSet[DicomTags.EchoNumbers].SetStringValue("1");
			theSet[DicomTags.MagneticFieldStrength].SetStringValue("1.500000");
			theSet[DicomTags.SpacingBetweenSlices].SetStringValue("10.00000");
			theSet[DicomTags.NumberOfPhaseEncodingSteps].SetStringValue("81");
			theSet[DicomTags.EchoTrainLength].SetStringValue("0");
			theSet[DicomTags.PercentSampling].SetStringValue("63.281250");
			theSet[DicomTags.PercentPhaseFieldOfView].SetStringValue("68.75000");
			theSet[DicomTags.DeviceSerialNumber].SetStringValue("1234");
			theSet[DicomTags.SoftwareVersions].SetStringValue("V1.0");
			theSet[DicomTags.ProtocolName].SetStringValue("2D EPI BH");
			theSet[DicomTags.TriggerTime].SetStringValue("14.000000");
			theSet[DicomTags.LowRRValue].SetStringValue("948");
			theSet[DicomTags.HighRRValue].SetStringValue("1178");
			theSet[DicomTags.IntervalsAcquired].SetStringValue("102");
			theSet[DicomTags.IntervalsRejected].SetStringValue("0");
			theSet[DicomTags.HeartRate].SetStringValue("56");
			theSet[DicomTags.ReceiveCoilName].SetStringValue("B");
			theSet[DicomTags.TransmitCoilName].SetStringValue("B");
			theSet[DicomTags.InPlanePhaseEncodingDirection].SetStringValue("COL");
			theSet[DicomTags.FlipAngle].SetStringValue("50.000000");
			theSet[DicomTags.PatientPosition].SetStringValue("HFS");
			theSet[DicomTags.StudyInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
			theSet[DicomTags.SeriesInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
			theSet[DicomTags.StudyId].SetStringValue("1933");
			theSet[DicomTags.SeriesNumber].SetStringValue("1");
			theSet[DicomTags.AcquisitionNumber].SetStringValue("7");
			theSet[DicomTags.InstanceNumber].SetStringValue("1");
			theSet[DicomTags.ImagePositionPatient].SetStringValue("-61.7564\\-212.04848\\-99.6208");
			theSet[DicomTags.ImageOrientationPatient].SetStringValue("0.861\\0.492\\0.126\\-0.2965");
			theSet[DicomTags.FrameOfReferenceUid].SetStringValue(DicomUid.GenerateUid().UID);
			theSet[DicomTags.PositionReferenceIndicator].SetStringValue(null);
			theSet[DicomTags.ImageComments].SetStringValue("Test MR Image");
			theSet[DicomTags.SamplesPerPixel].SetStringValue("1");
			theSet[DicomTags.PhotometricInterpretation].SetStringValue("MONOCHROME2");
			theSet[DicomTags.Rows].SetStringValue("256");
			theSet[DicomTags.Columns].SetStringValue("256");
			theSet[DicomTags.PixelSpacing].SetStringValue("1.367188");
			theSet[DicomTags.BitsAllocated].SetStringValue("16");
			theSet[DicomTags.BitsStored].SetStringValue("12");
			theSet[DicomTags.HighBit].SetStringValue("11");
			theSet[DicomTags.PixelRepresentation].SetStringValue("0");
			theSet[DicomTags.WindowCenter].SetStringValue("238");
			theSet[DicomTags.WindowWidth].SetStringValue("471");
            theSet[DicomTags.RescaleSlope].SetStringValue("1.1234567890123");
            theSet[DicomTags.RescaleIntercept].SetStringValue("0.0123456789012");

			uint length = 256 * 256 * 2;

			DicomAttributeOW pixels = new DicomAttributeOW(DicomTags.PixelData);

			byte[] pixelArray = new byte[length];

			for (uint i = 0; i < length; i += 2)
				pixelArray[i] = (byte)(i % 255);

			pixels.Values = pixelArray;

			theSet[DicomTags.PixelData] = pixels;

			DicomSequenceItem item = new DicomSequenceItem();
			theSet[DicomTags.RequestAttributesSequence].AddSequenceItem(item);

			item[DicomTags.RequestedProcedureId].SetStringValue("MRR1234");
			item[DicomTags.ScheduledProcedureStepId].SetStringValue("MRS1234");

			item = new DicomSequenceItem();
			theSet[DicomTags.RequestAttributesSequence].AddSequenceItem(item);

			item[DicomTags.RequestedProcedureId].SetStringValue("MR2R1234");
			item[DicomTags.ScheduledProcedureStepId].SetStringValue("MR2S1234");

			DicomSequenceItem studyItem = new DicomSequenceItem();

			item[DicomTags.ReferencedStudySequence].AddSequenceItem(studyItem);

			studyItem[DicomTags.ReferencedSopClassUid].SetStringValue(SopClass.MrImageStorageUid);
			studyItem[DicomTags.ReferencedSopInstanceUid].SetStringValue("1.2.3.4.5.6.7.8.9");

		}
Example #9
0
        public void SetupMultiframeXA(DicomAttributeCollection theSet, uint rows, uint columns, uint frames)
        {
            DateTime studyTime = DateTime.Now;

            theSet[DicomTags.SpecificCharacterSet].SetStringValue("ISO_IR 100");
            theSet[DicomTags.ImageType].SetStringValue("DERIVED\\SECONDARY\\SINGLE PLANE\\SINGLE A");
            theSet[DicomTags.InstanceCreationDate].SetStringValue(DateParser.ToDicomString(DateTime.Now));
            theSet[DicomTags.InstanceCreationTime].SetStringValue(TimeParser.ToDicomString(DateTime.Now));
            theSet[DicomTags.SopClassUid].SetStringValue(SopClass.XRayAngiographicImageStorageUid);
            theSet[DicomTags.SopInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
            theSet[DicomTags.StudyDate].SetStringValue(DateParser.ToDicomString(studyTime));
            theSet[DicomTags.StudyTime].SetStringValue(TimeParser.ToDicomString(studyTime));
            theSet[DicomTags.SeriesDate].SetStringValue(DateParser.ToDicomString(studyTime));
            theSet[DicomTags.SeriesTime].SetStringValue(TimeParser.ToDicomString(studyTime));
            theSet[DicomTags.AccessionNumber].SetStringValue("A4567");
            theSet[DicomTags.Modality].SetStringValue("XA");
            theSet[DicomTags.Manufacturer].SetStringValue("ClearCanvas");
            theSet[DicomTags.InstitutionName].SetStringValue("KardiologieUniklinikHeidelberg");
            theSet[DicomTags.ReferringPhysiciansName].SetStringValue("Last^First");
            theSet[DicomTags.StudyDescription].SetStringValue("HEART");
            theSet[DicomTags.SeriesDescription].SetStringValue("Heart 2D EPI BH TRA");
            theSet[DicomTags.PatientsName].SetStringValue("Patient^Test");
            theSet[DicomTags.PatientId].SetStringValue("ID123-45-9999");
            theSet[DicomTags.PatientsBirthDate].SetStringValue("19600101");
            theSet[DicomTags.PatientsSex].SetStringValue("M");
            theSet[DicomTags.PatientsWeight].SetStringValue("80");
            theSet[DicomTags.PatientsSize].SetStringValue("10.000244140625");
            theSet[DicomTags.Kvp].SetStringValue("80");
            theSet[DicomTags.ProtocolName].SetStringValue("25  FPS Koronarien");
            theSet[DicomTags.FrameTime].SetStringValue("40");
            theSet[DicomTags.FrameDelay].SetStringValue("0");
            theSet[DicomTags.DistanceSourceToDetector].SetStringValue("1018");
            theSet[DicomTags.ExposureTime].SetStringValue("7");
            theSet[DicomTags.XRayTubeCurrent].SetStringValue("815");
            theSet[DicomTags.RadiationSetting].SetStringValue("GR");
            theSet[DicomTags.IntensifierSize].SetStringValue("169.99998");
            theSet[DicomTags.PositionerMotion].SetStringValue("STATIC");
            theSet[DicomTags.PositionerPrimaryAngle].SetStringValue("-40.2999999");
            theSet[DicomTags.PositionerSecondaryAngle].SetStringValue("-15.5");
            theSet[DicomTags.DeviceSerialNumber].SetStringValue("1234");
            theSet[DicomTags.SoftwareVersions].SetStringValue("V1.0");
            theSet[DicomTags.StudyInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
            theSet[DicomTags.SeriesInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
            theSet[DicomTags.StudyId].SetStringValue("20021208125233");
            theSet[DicomTags.SeriesNumber].SetStringValue("1");
            theSet[DicomTags.AcquisitionNumber].SetStringValue("3");
            theSet[DicomTags.InstanceNumber].SetStringValue("13");
            theSet[DicomTags.PatientOrientation].SetNullValue();
            theSet[DicomTags.ImagesInAcquisition].SetStringValue("1");
            theSet[DicomTags.SamplesPerPixel].SetStringValue("1");
            theSet[DicomTags.PhotometricInterpretation].SetStringValue("MONOCHROME2");
            theSet[DicomTags.NumberOfFrames].SetUInt32(0, frames);
            theSet[DicomTags.Rows].SetUInt32(0, rows);
            theSet[DicomTags.Columns].SetUInt32(0, columns);
            theSet[DicomTags.FrameIncrementPointer].SetUInt32(0, DicomTags.FrameTime);
            theSet[DicomTags.BitsAllocated].SetStringValue("8");
            theSet[DicomTags.BitsStored].SetStringValue("8");
            theSet[DicomTags.HighBit].SetStringValue("7");
            theSet[DicomTags.PixelRepresentation].SetStringValue("0");
            theSet[DicomTags.WindowCenter].SetStringValue("128");
            theSet[DicomTags.WindowWidth].SetStringValue("204.8");
            theSet[DicomTags.PerformedProcedureStepStartDate].SetStringValue("20080219");
            theSet[DicomTags.PerformedProcedureStepStartTime].SetStringValue("143600");
            theSet[DicomTags.PerformedProcedureStepId].SetStringValue("UNKNOWN");

            // Null SQ Test
            theSet[DicomTags.ReferencedStudySequence].SetNullValue();

            // FL & FD tags for testing
            theSet[DicomTags.SlabThickness].SetFloat64(0, 0.1234567d);
            theSet[DicomTags.CalciumScoringMassFactorPatient].SetFloat32(0, 0.7654321f);

            uint length = rows * columns * frames;

            if (length % 2 == 1)
            {
                length++;
            }
            DicomAttributeOW pixels = new DicomAttributeOW(DicomTags.PixelData);

            byte[] pixelArray = new byte[length];
            pixelArray[length - 1] = 0x00; // Padding char

            for (uint frameCount = 0; frameCount < frames; frameCount++)
            {
                for (uint i = frameCount * rows * columns, val = frameCount + 1; i < (frameCount + 1) * rows * columns; i++, val++)
                {
                    pixelArray[i] = (byte)(val % 255);
                }
            }

            pixels.Values = pixelArray;

            theSet[DicomTags.PixelData] = pixels;

            DicomSequenceItem item = new DicomSequenceItem();

            theSet[DicomTags.RequestAttributesSequence].AddSequenceItem(item);

            item[DicomTags.RequestedProcedureId].SetStringValue("XA123");
            item[DicomTags.ScheduledProcedureStepId].SetStringValue("XA1234");

            item = new DicomSequenceItem();
            theSet[DicomTags.RequestAttributesSequence].AddSequenceItem(item);

            item[DicomTags.RequestedProcedureId].SetStringValue("XA567");
            item[DicomTags.ScheduledProcedureStepId].SetStringValue("XA5678");
        }
Example #10
0
        public void SetupSecondaryCapture(DicomAttributeCollection theSet)
        {
            DateTime studyTime = DateTime.Now;

            theSet[DicomTags.SpecificCharacterSet].SetStringValue("ISO_IR 100");
            theSet[DicomTags.ImageType].SetStringValue("ORIGINAL\\PRIMARY\\OTHER\\");
            theSet[DicomTags.InstanceCreationDate].SetStringValue(DateParser.ToDicomString(DateTime.Now));
            theSet[DicomTags.InstanceCreationTime].SetStringValue(TimeParser.ToDicomString(DateTime.Now));
            theSet[DicomTags.SopClassUid].SetStringValue(SopClass.SecondaryCaptureImageStorageUid);
            theSet[DicomTags.SopInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
            theSet[DicomTags.StudyDate].SetStringValue(DateParser.ToDicomString(studyTime));
            theSet[DicomTags.StudyTime].SetStringValue(TimeParser.ToDicomString(studyTime));
            theSet[DicomTags.SeriesDate].SetStringValue(DateParser.ToDicomString(studyTime));
            theSet[DicomTags.SeriesTime].SetStringValue(TimeParser.ToDicomString(studyTime));
            theSet[DicomTags.AccessionNumber].SetStringValue("A1234");
            theSet[DicomTags.Modality].SetStringValue("MR");
            theSet[DicomTags.Manufacturer].SetStringValue("ClearCanvas");
            theSet[DicomTags.ManufacturersModelName].SetNullValue();
            theSet[DicomTags.InstitutionName].SetStringValue("Toronto General Hospital");
            theSet[DicomTags.ReferringPhysiciansName].SetStringValue("Last^First");
            theSet[DicomTags.StudyDescription].SetStringValue("TEST");
            theSet[DicomTags.SeriesDescription].SetStringValue("TEST");
            theSet[DicomTags.PatientsName].SetStringValue("Patient^Test");
            theSet[DicomTags.PatientId].SetStringValue("ID123-45-9999");
            theSet[DicomTags.PatientsBirthDate].SetStringValue("19600102");
            theSet[DicomTags.PatientsSize].SetStringValue("10.000244140625");
            theSet[DicomTags.SequenceVariant].SetStringValue("OTHER");
            theSet[DicomTags.DeviceSerialNumber].SetStringValue("1234");
            theSet[DicomTags.SoftwareVersions].SetStringValue("V1.0");
            theSet[DicomTags.PatientPosition].SetStringValue("HFS");
            theSet[DicomTags.StudyInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
            theSet[DicomTags.SeriesInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
            theSet[DicomTags.StudyId].SetStringValue("1933");
            theSet[DicomTags.SeriesNumber].SetStringValue("1");
            theSet[DicomTags.InstanceNumber].SetStringValue("1");
            theSet[DicomTags.ImageComments].SetStringValue("Test SC Image");
            theSet[DicomTags.SamplesPerPixel].SetStringValue("1");
            theSet[DicomTags.PhotometricInterpretation].SetStringValue("MONOCHROME2");
            theSet[DicomTags.Rows].SetStringValue("256");
            theSet[DicomTags.Columns].SetStringValue("256");
            theSet[DicomTags.BitsAllocated].SetStringValue("16");
            theSet[DicomTags.BitsStored].SetStringValue("12");
            theSet[DicomTags.HighBit].SetStringValue("11");
            theSet[DicomTags.PixelRepresentation].SetStringValue("0");

            uint length = 256 * 256 * 2;

            DicomAttributeOW pixels = new DicomAttributeOW(DicomTags.PixelData);

            byte[] pixelArray = new byte[length];

            for (uint i = 0; i < length; i += 2)
            {
                pixelArray[i] = (byte)(i % 255);
            }

            pixels.Values = pixelArray;

            theSet[DicomTags.PixelData] = pixels;

            DicomSequenceItem item = new DicomSequenceItem();

            theSet[DicomTags.RequestAttributesSequence].AddSequenceItem(item);

            item[DicomTags.RequestedProcedureId].SetStringValue("MRR1234");
            item[DicomTags.ScheduledProcedureStepId].SetStringValue("MRS1234");

            item = new DicomSequenceItem();
            theSet[DicomTags.RequestAttributesSequence].AddSequenceItem(item);

            item[DicomTags.RequestedProcedureId].SetStringValue("MR2R1234");
            item[DicomTags.ScheduledProcedureStepId].SetStringValue("MR2S1234");

            DicomSequenceItem studyItem = new DicomSequenceItem();

            item[DicomTags.ReferencedStudySequence].AddSequenceItem(studyItem);

            studyItem[DicomTags.ReferencedSopClassUid].SetStringValue(SopClass.SecondaryCaptureImageStorageUid);
            studyItem[DicomTags.ReferencedSopInstanceUid].SetStringValue("1.2.3.4.5.6.7.8.9");
        }
Example #11
0
        public void SetupMR(DicomAttributeCollection theSet)
        {
            DateTime studyTime = DateTime.Now;

            theSet[DicomTags.SpecificCharacterSet].SetStringValue("ISO_IR 100");
            theSet[DicomTags.ImageType].SetStringValue("ORIGINAL\\PRIMARY\\OTHER\\M\\FFE");
            theSet[DicomTags.InstanceCreationDate].SetStringValue(DateParser.ToDicomString(DateTime.Now));
            theSet[DicomTags.InstanceCreationTime].SetStringValue(TimeParser.ToDicomString(DateTime.Now));
            theSet[DicomTags.AcquisitionDatetime].SetDateTime(0, DateTime.Now);
            theSet[DicomTags.SopClassUid].SetStringValue(SopClass.MrImageStorageUid);
            theSet[DicomTags.SopInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
            theSet[DicomTags.StudyDate].SetStringValue(DateParser.ToDicomString(studyTime));
            theSet[DicomTags.StudyTime].SetStringValue(TimeParser.ToDicomString(studyTime));
            theSet[DicomTags.SeriesDate].SetStringValue(DateParser.ToDicomString(studyTime));
            theSet[DicomTags.SeriesTime].SetStringValue(TimeParser.ToDicomString(studyTime));
            theSet[DicomTags.AccessionNumber].SetStringValue("A1234");
            theSet[DicomTags.Modality].SetStringValue("MR");
            theSet[DicomTags.Manufacturer].SetStringValue("ClearCanvas");
            theSet[DicomTags.ManufacturersModelName].SetNullValue();
            theSet[DicomTags.InstitutionName].SetStringValue("Mount Sinai Hospital");
            theSet[DicomTags.ReferringPhysiciansName].SetStringValue("Last^First");
            theSet[DicomTags.StudyDescription].SetStringValue("HEART");
            theSet[DicomTags.SeriesDescription].SetStringValue("Heart 2D EPI BH TRA");
            theSet[DicomTags.PatientsName].SetStringValue("Patient^Test");
            theSet[DicomTags.PatientId].SetStringValue("ID123-45-9999");
            theSet[DicomTags.PatientsBirthDate].SetStringValue("19600101");
            theSet[DicomTags.PatientsSex].SetStringValue("M");
            theSet[DicomTags.PatientsWeight].SetStringValue("70");
            theSet[DicomTags.PatientsSize].SetStringValue("10.000244140625");
            theSet[DicomTags.PatientsAge].SetStringValue("035Y");
            theSet[DicomTags.SequenceVariant].SetStringValue("OTHER");
            theSet[DicomTags.ScanOptions].SetStringValue("CG");
            theSet[DicomTags.MrAcquisitionType].SetStringValue("2D");
            theSet[DicomTags.SliceThickness].SetStringValue("10.000000");
            theSet[DicomTags.RepetitionTime].SetStringValue("857.142883");
            theSet[DicomTags.EchoTime].SetStringValue("8.712100");
            theSet[DicomTags.NumberOfAverages].SetStringValue("1");
            theSet[DicomTags.ImagingFrequency].SetStringValue("63.901150");
            theSet[DicomTags.ImagedNucleus].SetStringValue("1H");
            theSet[DicomTags.EchoNumbers].SetStringValue("1");
            theSet[DicomTags.MagneticFieldStrength].SetStringValue("1.500000");
            theSet[DicomTags.SpacingBetweenSlices].SetStringValue("10.00000");
            theSet[DicomTags.NumberOfPhaseEncodingSteps].SetStringValue("81");
            theSet[DicomTags.EchoTrainLength].SetStringValue("0");
            theSet[DicomTags.PercentSampling].SetStringValue("63.281250");
            theSet[DicomTags.PercentPhaseFieldOfView].SetStringValue("68.75000");
            theSet[DicomTags.DeviceSerialNumber].SetStringValue("1234");
            theSet[DicomTags.SoftwareVersions].SetStringValue("V1.0");
            theSet[DicomTags.ProtocolName].SetStringValue("2D EPI BH");
            theSet[DicomTags.TriggerTime].SetStringValue("14.000000");
            theSet[DicomTags.LowRRValue].SetStringValue("948");
            theSet[DicomTags.HighRRValue].SetStringValue("1178");
            theSet[DicomTags.IntervalsAcquired].SetStringValue("102");
            theSet[DicomTags.IntervalsRejected].SetStringValue("0");
            theSet[DicomTags.HeartRate].SetStringValue("56");
            theSet[DicomTags.ReceiveCoilName].SetStringValue("B");
            theSet[DicomTags.TransmitCoilName].SetStringValue("B");
            theSet[DicomTags.InPlanePhaseEncodingDirection].SetStringValue("COL");
            theSet[DicomTags.FlipAngle].SetStringValue("50.000000");
            theSet[DicomTags.PatientPosition].SetStringValue("HFS");
            theSet[DicomTags.StudyInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
            theSet[DicomTags.SeriesInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
            theSet[DicomTags.StudyId].SetStringValue("1933");
            theSet[DicomTags.SeriesNumber].SetStringValue("1");
            theSet[DicomTags.AcquisitionNumber].SetStringValue("7");
            theSet[DicomTags.InstanceNumber].SetStringValue("1");
            theSet[DicomTags.ImagePositionPatient].SetStringValue("-61.7564\\-212.04848\\-99.6208");
            theSet[DicomTags.ImageOrientationPatient].SetStringValue("0.861\\0.492\\0.126\\-0.2965");
            theSet[DicomTags.FrameOfReferenceUid].SetStringValue(DicomUid.GenerateUid().UID);
            theSet[DicomTags.PositionReferenceIndicator].SetStringValue(null);
            theSet[DicomTags.ImageComments].SetStringValue("Test MR Image");
            theSet[DicomTags.SamplesPerPixel].SetStringValue("1");
            theSet[DicomTags.PhotometricInterpretation].SetStringValue("MONOCHROME2");
            theSet[DicomTags.Rows].SetStringValue("256");
            theSet[DicomTags.Columns].SetStringValue("256");
            theSet[DicomTags.PixelSpacing].SetStringValue("1.367188\\1.367188");
            theSet[DicomTags.BitsAllocated].SetStringValue("16");
            theSet[DicomTags.BitsStored].SetStringValue("12");
            theSet[DicomTags.HighBit].SetStringValue("11");
            theSet[DicomTags.PixelRepresentation].SetStringValue("0");
            theSet[DicomTags.WindowCenter].SetStringValue("238");
            theSet[DicomTags.WindowWidth].SetStringValue("471");
            theSet[DicomTags.RescaleSlope].SetStringValue("1.1234567890123");
            theSet[DicomTags.RescaleIntercept].SetStringValue("0.0123456789012");

            uint length = 256 * 256 * 2;

            DicomAttributeOW pixels = new DicomAttributeOW(DicomTags.PixelData);

            byte[] pixelArray = new byte[length];

            for (uint i = 0; i < length; i += 2)
            {
                pixelArray[i] = (byte)(i % 255);
            }

            pixels.Values = pixelArray;

            theSet[DicomTags.PixelData] = pixels;

            DicomSequenceItem item = new DicomSequenceItem();

            theSet[DicomTags.RequestAttributesSequence].AddSequenceItem(item);

            item[DicomTags.RequestedProcedureId].SetStringValue("MRR1234");
            item[DicomTags.ScheduledProcedureStepId].SetStringValue("MRS1234");

            item = new DicomSequenceItem();
            theSet[DicomTags.RequestAttributesSequence].AddSequenceItem(item);

            item[DicomTags.RequestedProcedureId].SetStringValue("MR2R1234");
            item[DicomTags.ScheduledProcedureStepId].SetStringValue("MR2S1234");

            DicomSequenceItem studyItem = new DicomSequenceItem();

            item[DicomTags.ReferencedStudySequence].AddSequenceItem(studyItem);

            studyItem[DicomTags.ReferencedSopClassUid].SetStringValue(SopClass.MrImageStorageUid);
            studyItem[DicomTags.ReferencedSopInstanceUid].SetStringValue("1.2.3.4.5.6.7.8.9");
        }
Example #12
0
        public DicomReadStatus Read(DicomTag stopAtTag, DicomReadOptions options)
        {
        	if (stopAtTag == null)
                stopAtTag = new DicomTag(0xFFFFFFFF, "Bogus Tag", "BogusTag", DicomVr.UNvr, false, 1, 1, false);

            // Counters:
            //  _remain - bytes remaining in stream
            //  _bytes - estimates bytes to end of dataset
            //  _read - number of bytes read from stream
            try
            {
                BytesNeeded = 0;
                _remain = _stream.Length - _stream.Position;

                while (_remain > 0)
                {
                    if (_inGroup2 && BytesRead >= _endGroup2)
                    {
                        _inGroup2 = false;
                        // Only change if we're still reading the meta info
                        if (Dataset.StartTagValue < DicomTags.TransferSyntaxUid)
                        {
                            TransferSyntax group2Syntax =
                                TransferSyntax.GetTransferSyntax(
                                    Dataset[DicomTags.TransferSyntaxUid].GetString(0, String.Empty));
                            if (group2Syntax == null)
                                throw new DicomException("Unsupported transfer syntax in group 2 elements");
                            TransferSyntax = group2Syntax;
                        }
                    }
                    uint tagValue;
					if (LastTagRead == null)
					{
						if (_remain < 4)
							return NeedMoreData(4);

						_pos = _stream.Position;
						ushort g = _reader.ReadUInt16();
						ushort e = _reader.ReadUInt16();
						tagValue = DicomTag.GetTagValue(g, e);
						if (DicomTag.IsPrivateGroup(g) && e > 0x00ff)
						{
							SaveTagRead = LastTagRead = DicomTagDictionary.GetDicomTag(g, e) ??
							       new DicomTag((uint) g << 16 | e, "Private Tag", "PrivateTag", DicomVr.UNvr, false, 1, uint.MaxValue, false);
						}
						else
						{
							if (e == 0x0000)
                                SaveTagRead = LastTagRead = new DicomTag((uint)g << 16 | e, "Group Length", "GroupLength", DicomVr.ULvr, false, 1, 1, false);
							else
							{
                                SaveTagRead = LastTagRead = DicomTagDictionary.GetDicomTag(g, e) ??
								       new DicomTag((uint) g << 16 | e, "Private Tag", "PrivateTag", DicomVr.UNvr, false, 1, uint.MaxValue, false);
							}
						}
						_remain -= 4;
						BytesEstimated += 4;
						BytesRead += 4;
					}
					else
						tagValue = LastTagRead.TagValue;

                    if ((tagValue >= stopAtTag.TagValue) 
						&& (_sqrs.Count == 0)) // only exit in root message when after stop tag
                        return DicomReadStatus.Success;

                	bool twoByteLength;
                	if (_vr == null)
                    {
						if (_syntax.ExplicitVr)
						{
							if (LastTagRead == DicomTag.Item ||
								LastTagRead == DicomTag.ItemDelimitationItem ||
								LastTagRead == DicomTag.SequenceDelimitationItem)
							{
								_vr = DicomVr.NONE;
								twoByteLength = _vr.Is16BitLengthField;
							}
							else
							{
								if (_remain < 2)
									return NeedMoreData(2);

								string vr = new string(_reader.ReadChars(2));
								_vr = DicomVr.GetVR(vr);
								twoByteLength = _vr.Is16BitLengthField;
								_remain -= 2;
								BytesEstimated += 2;
								BytesRead += 2;
								if (LastTagRead.VR.Equals(DicomVr.UNvr))
								{
									LastTagRead = new DicomTag(LastTagRead.TagValue, "Private Tag", "PrivateTag", _vr, false, 1, uint.MaxValue, false);
									if (vr.Equals("??"))
										twoByteLength = true;
								}
								else if (!LastTagRead.VR.Equals(_vr))
								{
									if (!vr.Equals("  "))
									{
										DicomTag tag =
											new DicomTag(LastTagRead.TagValue, LastTagRead.Name, LastTagRead.VariableName, _vr, LastTagRead.MultiVR,
														 LastTagRead.VMLow, LastTagRead.VMHigh,
														 LastTagRead.Retired);
										LastTagRead = tag;

										; // TODO, log something
									}
								}
							}
						}
						else
						{
							_vr = LastTagRead.VR;
							twoByteLength = _vr.Is16BitLengthField;
						}

                        if (_vr == DicomVr.UNvr)
                        {
                            if (LastTagRead.IsPrivate)
                            {
								if (LastTagRead.Element <= 0x00ff && LastTagRead.Element >= 0x0010)
                                {
                                    // Reset the tag with the right VR and a more descriptive name.
                                    LastTagRead = new DicomTag(LastTagRead.TagValue, "Private Creator Code", "PrivateCreatorCode", DicomVr.LOvr, false, 1, uint.MaxValue, false);

                                    // private creator id
                                    // Only set the VR to LO for Implicit VR, if we do it for
                                    // Explicit VR syntaxes, we would incorrectly read the tag 
                                    // length below.
                                    if (!_syntax.ExplicitVr)
                                        _vr = DicomVr.LOvr;
                                    
                                }
                                else if (_stream.CanSeek && Flags.IsSet(options, DicomReadOptions.AllowSeekingForContext))
                                {
                                    // attempt to identify private sequence by checking if the tag has
									// an undefined length
                                    long pos = _stream.Position;

									int bytesToCheck = _syntax.ExplicitVr ? 6 : 4;

									if (_remain >= bytesToCheck)
									{
										if (_syntax.ExplicitVr)
											_reader.ReadUInt16();

										uint l = _reader.ReadUInt32();
										if (l == UndefinedLength)
											_vr = DicomVr.SQvr;
									}
                                	_stream.Position = pos;
                                }
                            }
                        }
                    }
                    else
						twoByteLength = _vr.Is16BitLengthField;

                    // Read the value length
					if (_len == UndefinedLength)
					{
						if (_syntax.ExplicitVr)
						{
							if (LastTagRead == DicomTag.Item ||
							    LastTagRead == DicomTag.ItemDelimitationItem ||
							    LastTagRead == DicomTag.SequenceDelimitationItem)
							{
								if (_remain < 4)
									return NeedMoreData(4);

								_len = _reader.ReadUInt32();
								_remain -= 4;
								BytesEstimated += 4;
								BytesRead += 4;
							}
							else
							{
								if (twoByteLength)
								{
									if (_remain < 2)
										return NeedMoreData(2);

									_len = _reader.ReadUInt16();
									_remain -= 2;
									BytesEstimated += 2;
									BytesRead += 2;
								}
								else
								{
									if (_remain < 6)
										return NeedMoreData(6);

									_reader.ReadByte();
									_reader.ReadByte();
									_len = _reader.ReadUInt32();
									_remain -= 6;
									BytesEstimated += 6;
									BytesRead += 6;
								}
							}
						}
						else
						{
							if (_remain < 4)
								return NeedMoreData(4);

							_len = _reader.ReadUInt32();
							_remain -= 4;
							BytesEstimated += 4;
							BytesRead += 4;
						}

						if ((_len != UndefinedLength)
						    && !_vr.Equals(DicomVr.SQvr)
						    && !(LastTagRead.Equals(DicomTag.Item)
						         && _fragment == null))
							BytesEstimated += _len;
					}

                	// If we have a private creator code, set the VR to LO, because
                    // that is what it is.  We must do this after we read the length
                    // so that the 32 bit length is read properly.
                    if ((LastTagRead.IsPrivate)
					  && (_vr.Equals(DicomVr.UNvr))
                      && (LastTagRead.Element <= 0x00ff))
                        _vr = DicomVr.LOvr;                    

                    if (_fragment != null)
                    {
                        // In the middle of parsing pixels
						if (LastTagRead == DicomTag.Item)
						{
							if (_remain < _len)
								return NeedMoreData(_remain - _len);

							if (Flags.IsSet(options, DicomReadOptions.StorePixelDataReferences)
							    && _fragment.HasOffsetTable)
							{
								FileReference reference = new FileReference(Filename, _stream.Position, _len, _endian, DicomVr.OBvr);
								DicomFragment fragment =
									new DicomFragment(reference);
								_fragment.AddFragment(fragment);
								_stream.Seek(_len, SeekOrigin.Current);
							}
							else
							{
								ByteBuffer data = new ByteBuffer(_endian, _len);
								data.CopyFrom(_stream, (int) _len);

								if (!_fragment.HasOffsetTable)
									_fragment.SetOffsetTable(data);
								else
								{
									DicomFragment fragment = new DicomFragment(data);
									_fragment.AddFragment(fragment);
								}
							}

							_remain -= _len;
							BytesRead += _len;
						}
						else if (LastTagRead == DicomTag.SequenceDelimitationItem)
						{
							Dataset[_fragment.Tag] = _fragment;
							_fragment = null;
						}
						else
						{
							Platform.Log(LogLevel.Error, "Encountered unexpected tag in stream: {0}", LastTagRead.ToString());
							// unexpected tag
							return DicomReadStatus.UnknownError;
						}

                    }
                    else if (_sqrs.Count > 0 &&
                                (LastTagRead == DicomTag.Item ||
                                LastTagRead == DicomTag.ItemDelimitationItem ||
                                LastTagRead == DicomTag.SequenceDelimitationItem))
                    {
                        SequenceRecord rec = _sqrs.Peek();

                        if (LastTagRead.Equals(DicomTag.Item))
                        {
                            if (_len != UndefinedLength)
                            {
                                if (_len > _remain)
                                    return NeedMoreData(_remain - _len);
                            }

                        	DicomSequenceItem ds;

							if (rec.Tag.TagValue.Equals(DicomTags.DirectoryRecordSequence))
							{
								DirectoryRecordSequenceItem dr = new DirectoryRecordSequenceItem
								                                 	{
								                                 		Offset = (uint) _pos
								                                 	};

								ds = dr;
							}
							else 
								ds = new DicomSequenceItem();

                            rec.Current = ds;
							if (rec.Tag.VR.Equals(DicomVr.UNvr))
							{
								DicomTag tag = new DicomTag(rec.Tag.TagValue, rec.Tag.Name,
								                            rec.Tag.VariableName, DicomVr.SQvr, rec.Tag.MultiVR, rec.Tag.VMLow,
								                            rec.Tag.VMHigh, rec.Tag.Retired);
								rec.Parent[tag].AddSequenceItem(ds);
							}
							else
                        		rec.Parent[rec.Tag].AddSequenceItem(ds);

                            // Specific character set is inherited, save it.  It will be overwritten
                            // if a new value of the tag is encountered in the sequence.
                            rec.Current.SpecificCharacterSet = rec.Parent.SpecificCharacterSet;

                            // save the sequence length
                            rec.Curpos = _pos + 8;
                            rec.Curlen = _len;

                            _sqrs.Pop();
                            _sqrs.Push(rec);

                            if (_len != UndefinedLength)
                            {
                                ByteBuffer data = new ByteBuffer(_endian, _len);
                                data.CopyFrom(_stream, (int)_len);
                                data.Stream.Position = 0;
                                _remain -= _len;
                                BytesRead += _len;

                                DicomStreamReader idsr = new DicomStreamReader(data.Stream)
                                                         	{
                                                         		Dataset = ds,
                                                         		TransferSyntax = rec.Tag.VR.Equals(DicomVr.UNvr)
                                                         		                 	? TransferSyntax.ImplicitVrLittleEndian
                                                         		                 	: _syntax,
                                                         		Filename = Filename
                                                         	};
                            	DicomReadStatus stat = idsr.Read(null, options);
                                if (stat != DicomReadStatus.Success)
                                {
									Platform.Log(LogLevel.Error, "Unexpected parsing error ({0}) when reading sequence attribute: {1}.", stat, rec.Tag.ToString());
                                    return stat;
                                }
                            }
                        }
                        else if (LastTagRead == DicomTag.ItemDelimitationItem)
                        {
                        }
                        else if (LastTagRead == DicomTag.SequenceDelimitationItem)
                        {
							SequenceRecord rec2 = _sqrs.Pop();
							if (rec2.Current==null)
								rec2.Parent[rec.Tag].SetNullValue();                      
                        }

                        if (rec.Len != UndefinedLength)
                        {
                            long end = rec.Pos + 8 + rec.Len;
                            if (_syntax.ExplicitVr)
                                end += 2 + 2;
                            if (_stream.Position >= end)
                            {
                                _sqrs.Pop();
                            }
                        }
                    }
                    else
                    {
                        if (_len == UndefinedLength)
                        {
							if (_vr.Equals(DicomVr.UNvr))
							{
								if (!_syntax.ExplicitVr)
								{
									_vr = DicomVr.SQvr;
									LastTagRead = LastTagRead.IsPrivate
									       	? new DicomTag(LastTagRead.TagValue, "Private Tag", "PrivateTag", DicomVr.SQvr, false, 1, uint.MaxValue, false)
									       	: new DicomTag(LastTagRead.TagValue, "Unknown Tag", "UnknownTag", DicomVr.SQvr, false, 1, uint.MaxValue, false);
								}
								else
								{
									// To handle this case, we'd have to add a new mechanism to transition the parser to implicit VR parsing,
									// and then return back to implicit once the parsing of the SQ is complete.
									Platform.Log(LogLevel.Error,
									             "Encountered unknown tag {0}, encoded as undefined length in an Explicit VR transfer syntax at offset {1}.  Unable to parse.",
									             LastTagRead, _stream.Position);
									return DicomReadStatus.UnknownError;
								}
							}

                        	if (_vr.Equals(DicomVr.SQvr))
                            {
                                SequenceRecord rec = new SequenceRecord
                                                     	{
                                                     		Parent = _sqrs.Count > 0
                                                     		         	? _sqrs.Peek().Current
                                                     		         	: Dataset,
                                                     		Current = null,
                                                     		Tag = LastTagRead,
                                                     		Len = UndefinedLength
                                                     	};

                            	_sqrs.Push(rec);
                            }
                            else
                            {
                                _fragment = new DicomFragmentSequence(LastTagRead);

                                Dataset.LoadDicomFields(_fragment);
                            }
                        }
                        else
                        {
							if (_vr.Equals(DicomVr.SQvr))
							{
								if (_len == 0)
								{
									DicomAttributeCollection ds;
									if (_sqrs.Count > 0)
									{
										SequenceRecord rec = _sqrs.Peek();
										ds = rec.Current;
									}
									else
										ds = Dataset;

									ds[LastTagRead].SetNullValue();
								}
								else
								{
									SequenceRecord rec = new SequenceRecord
									                     	{
									                     		Len = _len,
									                     		Pos = _pos,
									                     		Tag = LastTagRead,
									                     		Parent = _sqrs.Count > 0
									                     		         	? _sqrs.Peek().Current
									                     		         	: Dataset
									                     	};

									_sqrs.Push(rec);
								}
							}
							else
							{
								if (_remain < _len)
									return NeedMoreData(_len - _remain);

								if ((LastTagRead.TagValue == DicomTags.PixelData)
								    && Flags.IsSet(options, DicomReadOptions.DoNotStorePixelDataInDataSet))
								{
									// Skip PixelData !!
									_stream.Seek((int) _len, SeekOrigin.Current);
									_remain -= _len;
									BytesRead += _len;
								}
								else if ((LastTagRead.TagValue == DicomTags.PixelData) &&
								         Flags.IsSet(options, DicomReadOptions.StorePixelDataReferences))
								{
									FileReference reference =
										new FileReference(Filename, _stream.Position, _len, _endian,
										                  LastTagRead.VR);
									_stream.Seek((int) _len, SeekOrigin.Current);

									if (LastTagRead.VR.Equals(DicomVr.OWvr))
									{
										DicomAttributeOW elem = new DicomAttributeOW(LastTagRead, reference);
										Dataset[LastTagRead] = elem;
									}
									else if (LastTagRead.VR.Equals(DicomVr.OBvr))
									{
										DicomAttributeOB elem = new DicomAttributeOB(LastTagRead, reference);
										Dataset[LastTagRead] = elem;
									}
									else
									{
										DicomAttributeOF elem = new DicomAttributeOF(LastTagRead, reference);
										Dataset[LastTagRead] = elem;
									}
									_remain -= _len;
									BytesRead += _len;
								}
								else
								{
									ByteBuffer bb = new ByteBuffer(_len);
									// If the tag is impacted by specific character set, 
									// set the encoding properly.
									if (LastTagRead.VR.SpecificCharacterSet)
									{
										if (_sqrs.Count > 0)
										{
											SequenceRecord rec = _sqrs.Peek();
											bb.SpecificCharacterSet = rec.Current.SpecificCharacterSet;
										}
										else
										{
											bb.SpecificCharacterSet = Dataset.SpecificCharacterSet;
										}
									}
                                    if (LastTagRead.VR.Equals(DicomVr.UNvr) 
                                        && !SaveTagRead.VR.Equals(DicomVr.UNvr)
                                        && !SaveTagRead.VR.Equals(DicomVr.SQvr)
                                        && Flags.IsSet(options, DicomReadOptions.UseDictionaryForExplicitUN))
                                    {
                                        LastTagRead = SaveTagRead;
                                        bb.Endian = Endian.Little;
                                    }
                                    else
                                    {
                                        bb.Endian = _endian;
                                    }

									bb.CopyFrom(_stream, (int) _len);


									DicomAttribute elem = LastTagRead.CreateDicomAttribute(bb);

									_remain -= _len;
									BytesRead += _len;


									if (_sqrs.Count > 0)
									{
										SequenceRecord rec = _sqrs.Peek();
										DicomAttributeCollection ds = rec.Current;

										if (elem.Tag.TagValue == DicomTags.SpecificCharacterSet)
										{
											ds.SpecificCharacterSet = elem.ToString();
										}

										if (LastTagRead.Element == 0x0000)
										{
											if (Flags.IsSet(options, DicomReadOptions.KeepGroupLengths))
												ds[LastTagRead] = elem;
										}
										else
											ds[LastTagRead] = elem;

										if (rec.Curlen != UndefinedLength)
										{
											long end = rec.Curpos + rec.Curlen;
											if (_stream.Position >= end)
											{
												rec.Current = null;
											}
										}
									}
									else
									{
										if (LastTagRead.TagValue == DicomTags.FileMetaInformationGroupLength)
										{
											// Save the end of the group 2 elements, so that we can automatically 
											// check and change our transfer syntax when needed.
											_inGroup2 = true;
											uint group2Len;
											elem.TryGetUInt32(0, out group2Len);
											_endGroup2 = BytesRead + group2Len;
										}
										else if (LastTagRead.TagValue == DicomTags.SpecificCharacterSet)
										{
											Dataset.SpecificCharacterSet = elem.ToString();
										}

										if (LastTagRead.Element == 0x0000)
										{
											if (Flags.IsSet(options, DicomReadOptions.KeepGroupLengths))
												Dataset[LastTagRead] = elem;
										}
										else
											Dataset[LastTagRead] = elem;
									}
								}
							}
                        }
                    }

                    LastTagRead = null;
                    _vr = null;
                    _len = UndefinedLength;
                }
                return DicomReadStatus.Success;
            }
            catch (EndOfStreamException e)
            {
                // should never happen
				Platform.Log(LogLevel.Error, "Unexpected exception when reading file: {0}", e.ToString());
                return DicomReadStatus.UnknownError;
            }
        }
Example #13
0
        //public void SaveEfilm(string efilmFullPath, ref string efilmOriginalSopInstanceUID)
        //{
        //    efilmOriginalSopInstanceUID = string.Empty;

        //}

        public void SaveEfilm(string efilmFullPath, ref string efilmOriginalSopInstanceUID, ref string efilmOriginalStudyInstanceUid, bool ifSaveEFilm)
        {
            efilmOriginalSopInstanceUID = string.Empty;

            try
            {
                Logger.LogFuncUp();

                if (_dicomDataHeader == null)
                {
                    return;
                }

                var wrtBmp = RenderControlWriteableBitmap();

                if (wrtBmp == null)
                {
                    throw new ApplicationException("ViewerControl Writeable Bitmap Render failed.");
                }



                byte[] data = ProcessImage(wrtBmp);
                Console.WriteLine(Convert.ToString(wrtBmp.PixelWidth) + " ,,,,," + Convert.ToString(wrtBmp.PixelHeight));

                ////MedViewerLayoutCell layoutCell = medViewerControl.LayoutManager.RootCell;
                ////MedViewerControlCell cell = GetControlCell(layoutCell);


                var pixelHeightTag = new DicomAttributeUS(new DicomTag(Pipeline.Dictionary.Tag.Rows));
                pixelHeightTag.SetUInt16(0, Convert.ToUInt16(wrtBmp.PixelHeight));
                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.Rows);
                _dicomDataHeader.AddDicomAttribute(pixelHeightTag);

                var pixelWidthTag = new DicomAttributeUS(new DicomTag(Pipeline.Dictionary.Tag.Columns));
                pixelWidthTag.SetUInt16(0, Convert.ToUInt16(wrtBmp.PixelWidth));
                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.Columns);
                _dicomDataHeader.AddDicomAttribute(pixelWidthTag);

                var bitStoredTag = new DicomAttributeUS(new DicomTag(Pipeline.Dictionary.Tag.BitsStored));
                bitStoredTag.SetUInt16(0, 8);
                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.BitsStored);
                _dicomDataHeader.AddDicomAttribute(bitStoredTag);

                var bitAllocatedTag = new DicomAttributeUS(new DicomTag(Pipeline.Dictionary.Tag.BitsAllocated));
                bitAllocatedTag.SetUInt16(0, 8);
                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.BitsAllocated);
                _dicomDataHeader.AddDicomAttribute(bitAllocatedTag);

                var hightBitTag = new DicomAttributeUS(new DicomTag(Pipeline.Dictionary.Tag.HighBit));
                hightBitTag.SetUInt16(0, 7);
                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.HighBit);
                _dicomDataHeader.AddDicomAttribute(hightBitTag);

                var pixelRepresentationTag = new DicomAttributeUS(new DicomTag(Pipeline.Dictionary.Tag.PixelRepresentation));
                pixelRepresentationTag.SetUInt16(0, 0);
                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.PixelRepresentation);
                _dicomDataHeader.AddDicomAttribute(pixelRepresentationTag);

                var rescaleSlopeTag = new DicomAttributeDS(new DicomTag(Pipeline.Dictionary.Tag.RescaleSlope));
                rescaleSlopeTag.SetString(0, "1");
                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.RescaleSlope);
                _dicomDataHeader.AddDicomAttribute(rescaleSlopeTag);

                var rescaleInterceptTag = new DicomAttributeDS(new DicomTag(Pipeline.Dictionary.Tag.RescaleIntercept));
                rescaleInterceptTag.SetString(0, "0");;
                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.RescaleIntercept);
                _dicomDataHeader.AddDicomAttribute(rescaleInterceptTag);


                ////insert Photometric Interpretation //maybe can fix inverse problem
                //var photometricInterpretationTag = new DicomAttributeUS(new DicomTag(Pipeline.Dictionary.Tag.PhotometricInterpretation));
                //rescaleInterceptTag.SetString(0, "MONOCHROME2");
                ////_dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.PhotometricInterpretation);
                //_dicomDataHeader.AddDicomAttribute(photometricInterpretationTag);
                //insert Photometric Interpretation
                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.PhotometricInterpretation);
                var photometricInterpretationTag = DicomAttribute.CreateAttribute(Pipeline.Dictionary.Tag.PhotometricInterpretation);
                if (!photometricInterpretationTag.SetString(0, "MONOCHROME2"))
                {
                    throw new Exception("Failed to Insert Columns to Data header");
                }
                _dicomDataHeader.AddDicomAttribute(photometricInterpretationTag);

                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.WindowWidth);
                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.WindowCenter);
                var windowWidthTag = new DicomAttributeDS(new DicomTag(Pipeline.Dictionary.Tag.WindowWidth));
                //var windowWidthTag = DicomAttribute.CreateAttribute(Pipeline.Dictionary.Tag.WindowWidth);
                windowWidthTag.SetString(0, "256");
                _dicomDataHeader.AddDicomAttribute(windowWidthTag);
                var windowCenterTag = new DicomAttributeDS(new DicomTag(Pipeline.Dictionary.Tag.WindowCenter));
                //var windowCenterTag = DicomAttribute.CreateAttribute(Pipeline.Dictionary.Tag.WindowCenter);
                windowCenterTag.SetString(0, "127");
                _dicomDataHeader.AddDicomAttribute(windowCenterTag);

                if (_dicomDataHeader.Contains(Pipeline.Dictionary.Tag.PixelData))
                {
                    _dicomDataHeader[Pipeline.Dictionary.Tag.PixelData].SetBytes(0, data);
                }
                else
                {
                    var pixelTag = new DicomAttributeOW(new DicomTag(Pipeline.Dictionary.Tag.PixelData));
                    pixelTag.SetBytes(0, data);
                    _dicomDataHeader.AddDicomAttribute(pixelTag);
                }
                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.ShutterShape);
                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.ShutterLowerHorizontalEdge);
                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.ShutterRightVerticalEdge);
                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.ShutterLeftVerticalEdge);
                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.ShutterUpperHorizontalEdge);
                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.ImageHorizontalFlip);
                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.ImageRotation);
                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.SeriesNumber);
                //_dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.);
                //AssembleTag();

                var uidManager        = McsfDatabaseDicomUIDManagerFactory.Instance().CreateUIDManager();
                var seriesInstanceUid = uidManager.CreateSeriesUID("1", "2", ""); //seriesUID; //
                var imageUid          = uidManager.CreateImageUID("");

                //_dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.SeriesInstanceUid);
                //var seriesInstanceUidTag = new DicomAttributeUI(new DicomTag(Pipeline.Dictionary.Tag.SeriesInstanceUid));
                //seriesInstanceUidTag.SetString(0, seriesInstanceUid);
                //_dicomDataHeader.AddDicomAttribute(seriesInstanceUidTag);

                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.SOPInstanceUID);
                var sopInstanceUidTag = new DicomAttributeUI(new DicomTag(Pipeline.Dictionary.Tag.SOPInstanceUID));
                sopInstanceUidTag.SetString(0, imageUid);
                _dicomDataHeader.AddDicomAttribute(sopInstanceUidTag);

                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.ImageType);
                var imageTypeCollection = ("DERIVED\\SECONDARY\\DISPLAY\\FILMING\\EFILM").Split('\\');
                InsertStringArrayDicomElement(_dicomDataHeader, Pipeline.Dictionary.Tag.ImageType, imageTypeCollection);

                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.ConversionType);
                var cTypeTag = new DicomAttributeCS(new DicomTag(Pipeline.Dictionary.Tag.ConversionType));
                cTypeTag.SetString(0, "WSD");
                _dicomDataHeader.AddDicomAttribute(cTypeTag);

                _dicomDataHeader.RemoveDicomAttribute(Pipeline.Dictionary.Tag.SeriesDescription);
                var seriesDescriptionTag = new DicomAttributeLO(new DicomTag(Pipeline.Dictionary.Tag.SeriesDescription));
                seriesDescriptionTag.SetString(0, "Electronic film_" + DateTime.Now.ToString());
                _dicomDataHeader.AddDicomAttribute(seriesDescriptionTag);

                _dicomConvertorProxy.SaveFile(_dicomDataHeader, efilmFullPath, _proxy);

                var medViewerControlCell = medViewerControl.LayoutManager.ControlCells.FirstOrDefault();
                if (medViewerControlCell != null)
                {
                    var currentPage = medViewerControlCell.Image.CurrentPage;
                    efilmOriginalSopInstanceUID = currentPage.SOPInstanceUID;
                    var dicomHeader = currentPage.ImageHeader.DicomHeader;
                    if (dicomHeader.ContainsKey(ServiceTagName.StudyInstanceUID))
                    {
                        efilmOriginalStudyInstanceUid = dicomHeader[ServiceTagName.StudyInstanceUID];
                    }
                }

                if (!ifSaveEFilm)
                {
                    return;
                }
                CreateSeries(efilmOriginalStudyInstanceUid, seriesInstanceUid);
                SaveEFilmInCommonSave(seriesInstanceUid);

                Logger.LogFuncDown();
            }
            catch (Exception ex)
            {
                Logger.LogFuncException(ex.Message + ex.StackTrace);
            }
            finally
            {
                medViewerControl.RemoveAll();
            }
        }