public IList <IStorageLocation> CreateMedia(DicomFile data) { if (null != MediaStorage) { string key = null; int framesCount = 1; List <IStorageLocation> locations = new List <IStorageLocation> ( ); if (StoreMultiFrames) { DicomPixelData pd; pd = DicomPixelData.CreateFrom(data); framesCount = pd.NumberOfFrames; } for (int frame = 1; frame <= framesCount; frame++) { var storeLocation = MediaStorage.GetLocation(new DicomMediaId(data.DataSet, frame, MediaType)); Upload(data, frame, storeLocation); locations.Add(storeLocation); } return(locations); } throw new InvalidOperationException("No MediaStorage service found"); }
public DicomPixelData GetPixelData(string seriesInstanceUid, string sopInstanceUid) { DicomPixelData pd = null; for (int i = 0; i < 5; i++) { // look at the cache first pd = DicomPixelDataCache.Find(_storage, _storage.StudyInstanceUid, seriesInstanceUid, sopInstanceUid); if (pd != null) { break; } try { pd = DicomPixelData.CreateFrom(_storage.GetSopInstancePath(seriesInstanceUid, sopInstanceUid), DicomReadOptions.StorePixelDataReferences); DicomPixelDataCache.Insert(_storage, _storage.StudyInstanceUid, seriesInstanceUid, sopInstanceUid, pd); break; } catch (FileNotFoundException) { throw; } catch (IOException) { var rand = new Random(); Thread.Sleep(rand.Next(100, 500)); } } return(pd); }
public static void LosslessImageTestWithConversion(TransferSyntax syntax, DicomFile theFile) { if (File.Exists(theFile.Filename)) { File.Delete(theFile.Filename); } DicomFile saveCopy = new DicomFile(theFile.Filename, theFile.MetaInfo.Copy(), theFile.DataSet.Copy()); theFile.ChangeTransferSyntax(syntax); theFile.Save(DicomWriteOptions.ExplicitLengthSequence); DicomFile newFile = new DicomFile(theFile.Filename); newFile.Load(DicomReadOptions.Default); newFile.ChangeTransferSyntax(saveCopy.TransferSyntax); string failureDescription; bool result = Compare(DicomPixelData.CreateFrom(newFile), DicomPixelData.CreateFrom(saveCopy), out failureDescription); Assert.IsTrue(result, failureDescription); Assert.IsFalse(newFile.DataSet.Equals(saveCopy.DataSet)); }
public void SavePixels(string filename) { DicomPixelData pd = DicomPixelData.CreateFrom(_dicomFile); if (File.Exists(filename)) { File.Delete(filename); } using (FileStream fs = new FileStream(filename, FileMode.CreateNew)) { byte[] ba; DicomCompressedPixelData compressed = pd as DicomCompressedPixelData; if (compressed != null) { ba = compressed.GetFrameFragmentData(0); } else { ba = pd.GetFrame(0); } fs.Write(ba, 0, ba.Length); fs.Flush(); fs.Close(); } }
protected override void Upload(DicomFile dicomObject, int frame, IStorageLocation storeLocation) { DicomPixelData pd = null; byte[] buffer = null; pd = DicomPixelData.CreateFrom(dicomObject); buffer = pd.GetFrame(frame - 1); storeLocation.Upload(buffer); }
public ImageStreamingContext(HttpListenerContext context) { Request = context.Request; Response = context.Response; NameValueCollection query = Request.QueryString; #region INIT STUFF FOR PERFORMANCE TESTING #if DEBUG if (query["testcompressed"] != null) { testCompressed = true; } else if (query["testuncompressed"] != null) { testUncompressed = true; } if (_testCompressedImage == null) { using (Stream stream = typeof(ImageStreamingContext).Assembly.GetManifestResourceStream("Macro.ImageServer.Services.Streaming.ImageStreaming.Test.TestSamples.compressed.dcm")) { DicomFile file = new DicomFile(); file.Load(stream); _testCompressedImage = DicomPixelData.CreateFrom(file); } } if (_testUncompressedImage == null) { using (Stream stream = typeof(ImageStreamingContext).Assembly.GetManifestResourceStream("Macro.ImageServer.Services.Streaming.ImageStreaming.Test.TestSamples.uncompressed.dcm")) { DicomFile file = new DicomFile(); file.Load(stream); _testUncompressedImage = DicomPixelData.CreateFrom(file); } } #endif #endregion _frameNumber = 0; if (query["FrameNumber"] != null) { int.TryParse(query["FrameNumber"], out _frameNumber); } _nextSeriesUid = query["nextSeriesUid"]; _nextSopUid = query["nextObjectUid"]; }
public DicomPixelData GetPixelData(string seriesInstanceUid, string sopInstanceUid, string nextSeriesInstanceUid, string nextSopInstanceUid) { DicomPixelData pd = null; for (int i = 0; i < 5; i++) { // look at the cache first pd = DicomPixelDataCache.Find(_storage, _storage.StudyInstanceUid, seriesInstanceUid, sopInstanceUid); if (pd != null) { break; } // Check if the file has been requested to open by the client string key = string.Format("ImageStreamPrefetchStream/{0}/{1}/{2}/{3}", _storage.ServerPartition.AeTitle, _storage.StudyInstanceUid, seriesInstanceUid, sopInstanceUid); Stream preopenStream = HttpRuntime.Cache[key] as Stream; if (preopenStream != null) { pd = DicomPixelData.CreateFrom(_storage.GetSopInstancePath(seriesInstanceUid, sopInstanceUid), preopenStream, DicomReadOptions.StorePixelDataReferences); DicomPixelDataCache.Insert(_storage, _storage.StudyInstanceUid, seriesInstanceUid, sopInstanceUid, pd); preopenStream.Close(); HttpRuntime.Cache.Remove(key); break; } else { try { pd = DicomPixelData.CreateFrom(_storage.GetSopInstancePath(seriesInstanceUid, sopInstanceUid), DicomReadOptions.StorePixelDataReferences); DicomPixelDataCache.Insert(_storage, _storage.StudyInstanceUid, seriesInstanceUid, sopInstanceUid, pd); break; } catch (FileNotFoundException) { throw; } catch (IOException) { Random rand = new Random(); Thread.Sleep(rand.Next(100, 500)); } } } OnPixelDataLoaded(sopInstanceUid, nextSeriesInstanceUid, nextSopInstanceUid); return(pd); }
public Stream Convert(DicomAttributeCollection ds) { DicomAttributeCollection command = new DicomAttributeCollection(); command[DicomTags.TransferSyntaxUid] = ds[DicomTags.TransferSyntaxUid]; DicomMessage message = new DicomMessage(command, ds); DicomPixelData pd = DicomPixelData.CreateFrom(message); string tempFile = System.IO.Path.GetTempFileName( ); System.IO.File.WriteAllBytes(tempFile, pd.GetFrame(0)); return(new DICOMcloud.Core.Storage.TempStream(new TempFile(tempFile))); }
protected override void Upload(DicomFile dicomObject, int frame, IStorageLocation storeLocation) { var frameIndex = frame - 1; if (dicomObject.TransferSyntax == TransferSyntax.JpegBaselineProcess1) { DicomCompressedPixelData pd = DicomPixelData.CreateFrom(dicomObject) as DicomCompressedPixelData; byte[] buffer = pd.GetFrameFragmentData(frameIndex); storeLocation.Upload(buffer); } else if (false) //TODO: handle compressed images properly! { DicomFile dcmJpeg = new DicomFile( ); DicomUncompressedPixelData unCompressed = DicomPixelData.CreateFrom(dicomObject) as DicomUncompressedPixelData; DicomCompressedPixelData compressed = new DicomCompressedPixelData(unCompressed); //compressed.ImageWidth = unCompressed.ImageWidth; //compressed.ImageHeight = unCompressed.HighBit; compressed.BitsStored = 8; compressed.BitsAllocated = 8; //compressed.HighBit = 7; compressed.SamplesPerPixel = 3; //compressed.PlanarConfiguration = 0; compressed.PhotometricInterpretation = "YBR_FULL_422"; compressed.TransferSyntax = TransferSyntax.JpegBaselineProcess1; byte[] imageBuffer = unCompressed.GetFrame(frameIndex); compressed.AddFrameFragment(imageBuffer); compressed.UpdateMessage(dcmJpeg); storeLocation.Upload(compressed.GetFrame(frameIndex)); //ClearCanvas.Dicom.Codec.Jpeg.Jpeg8Codec codec = new ClearCanvas.Dicom.Codec.Jpeg.Jpeg8Codec (ClearCanvas.Dicom.Codec.Jpeg.JpegMode.Baseline, 0, 0 ) ; //ClearCanvas.Dicom.Codec.Jpeg.DicomJpegParameters jparam = new ClearCanvas.Dicom.Codec.Jpeg.DicomJpegParameters ( ) ; //jparam. //codec. //codec.Encode ( ) } }
public static void LosslessImageTest(TransferSyntax syntax, DicomFile theFile) { if (File.Exists(theFile.Filename)) { File.Delete(theFile.Filename); } DicomFile saveCopy = new DicomFile(theFile.Filename, theFile.MetaInfo.Copy(), theFile.DataSet.Copy()); theFile.ChangeTransferSyntax(syntax); theFile.Save(DicomWriteOptions.ExplicitLengthSequence); saveCopy.Filename = "SCLosslessUncompressed.dcm"; saveCopy.Save(DicomWriteOptions.ExplicitLengthSequence); DicomFile newFile = new DicomFile(theFile.Filename); newFile.Load(DicomReadOptions.Default); newFile.ChangeTransferSyntax(saveCopy.TransferSyntax); newFile.Filename = "SCLosslessUncompressedPostCompression.dcm"; newFile.Save(DicomWriteOptions.ExplicitLengthSequence); string failureDescription; bool result = Compare(DicomPixelData.CreateFrom(newFile), DicomPixelData.CreateFrom(saveCopy), out failureDescription); Assert.IsTrue(result, failureDescription); List <DicomAttributeComparisonResult> list = new List <DicomAttributeComparisonResult>(); result = newFile.DataSet.Equals(saveCopy.DataSet, ref list); StringBuilder sb = new StringBuilder(); foreach (DicomAttributeComparisonResult compareResult in list) { sb.AppendFormat("Comparison Failure: {0}, ", compareResult.Details); } Assert.IsTrue(result, sb.ToString()); }
public static void LosslessImageTestWithBitsAllocatedConversion(TransferSyntax syntax, DicomFile theFile) { if (File.Exists(theFile.Filename)) { File.Delete(theFile.Filename); } DicomFile saveCopy = new DicomFile(theFile.Filename, theFile.MetaInfo.Copy(), theFile.DataSet.Copy()); theFile.ChangeTransferSyntax(syntax); theFile.Save(DicomWriteOptions.ExplicitLengthSequence); DicomFile newFile = new DicomFile(theFile.Filename); newFile.Load(DicomReadOptions.Default); newFile.ChangeTransferSyntax(saveCopy.TransferSyntax); string failureDescription; var newPd = DicomPixelData.CreateFrom(newFile); var oldPd = DicomPixelData.CreateFrom(saveCopy); bool result = Compare(newPd, oldPd, out failureDescription); Assert.IsFalse(result, failureDescription); Assert.IsFalse(newFile.DataSet.Equals(saveCopy.DataSet)); DicomAttributeCollection newDataSet = newFile.DataSet.Copy(true, true, true); DicomAttributeCollection oldDataSet = theFile.DataSet.Copy(true, true, true); oldDataSet.RemoveAttribute(DicomTags.BitsAllocated); newDataSet.RemoveAttribute(DicomTags.BitsAllocated); oldDataSet.RemoveAttribute(DicomTags.PixelData); newDataSet.RemoveAttribute(DicomTags.PixelData); var results = new List <DicomAttributeComparisonResult>(); bool check = oldDataSet.Equals(newDataSet, ref results); Assert.IsTrue(check, results.Count > 0 ? CollectionUtils.FirstElement(results).Details : string.Empty); for (int i = 0; i < oldPd.NumberOfFrames; i++) { var frame = oldPd.GetFrame(i); var convertedFrame = DicomUncompressedPixelData.ToggleBitDepth(frame, frame.Length, oldPd.UncompressedFrameSize, oldPd.BitsStored, oldPd.BitsAllocated); var newFrame = newPd.GetFrame(i); int pixelsVarying = 0; decimal totalVariation = 0.0m; for (int j = 0; j < convertedFrame.Length; j++) { if (convertedFrame[j] != newFrame[j]) { pixelsVarying++; totalVariation += Math.Abs(convertedFrame[i] - newFrame[i]); } } if (pixelsVarying > 0) { Assert.Fail(String.Format( "Tag (7fe0,0010) Pixel Data: {0} of {1} pixels varying, average difference: {2}", pixelsVarying, convertedFrame.Length, totalVariation / pixelsVarying)); } } }
public static void CreateSeriesGraphicsForSeg(IPresentationImage presentationImage, Seg seg, SegmentationDocument segmentationDocument, IDicomMessageSopDataSource dicomMessageSopDataSourceSop) { Platform.CheckForNullReference(presentationImage, "presentationImage"); Platform.CheckForNullReference(seg, "seg"); Platform.CheckForNullReference(segmentationDocument, "segmentationDocument"); SegmentImageData segImageData = seg.SegmentImageData; if (segImageData == null) { Platform.Log(LogLevel.Error, "Cannot create segmentation graphics when no segmentation imaging data is provided"); return; } var imageSopProvider = presentationImage as IImageSopProvider; if (imageSopProvider == null) { Platform.Log(LogLevel.Error, "Failed to populate SegFrameGraphics collection. Image is not an ImageSopProvider"); return; } DicomPixelData segmentationPixelData = DicomPixelData.CreateFrom(dicomMessageSopDataSourceSop.SourceMessage); var rawPixelData = (byte[])dicomMessageSopDataSourceSop.SourceMessage.DataSet.GetAttribute(DicomTags.PixelData).Values; var pixelDataGetter = new Func <int, byte[]>(frameIndex => { if (segImageData.BitsStored == 1) { // Do unpacking int frameLength = segImageData.Rows * segImageData.Columns; var overlayData = new OverlayData(frameIndex * frameLength, segImageData.Rows, segImageData.Columns, false, rawPixelData); return(overlayData.Unpack()); } if (segImageData.BitsStored == 8) { return(segmentationPixelData.GetFrame(frameIndex)); } throw new InvalidDataException( "Segmentation objects need to have BitsStored as either 1 or 8"); }); // NOTE: SegmentFrameData was already sorted foreach (SegmentFrameData segmentFrameData in segImageData.SegmentFrameData) { IPresentationImage segPresentationImage = null; // Get the presentation image if we have an image reference string referencedSopInstanceUid = segmentFrameData.ReferencedSopInstanceUid; int referencedImageFrameNumber = segmentFrameData.ReferencedFrameNumber ?? 1; if (!string.IsNullOrEmpty(referencedSopInstanceUid)) { segPresentationImage = presentationImage.ParentDisplaySet.PresentationImages.OfType <IImageSopProvider>() .FirstOrDefault(curImageSopProvider => curImageSopProvider != null && curImageSopProvider.ImageSop.SopInstanceUid == referencedSopInstanceUid && curImageSopProvider.Frame.FrameNumber == referencedImageFrameNumber) as IPresentationImage; } // Location defaults to 0, 0 unless determined otherwise from image position and image orientation var segLocation = new PointF(); // Get the presentation image from the image position and orientation if (segmentFrameData.ImagePositionPatient != null && segmentFrameData.ImagePositionPatient.Count() > 2 && segmentFrameData.ImageOrientationPatient != null && segmentFrameData.ImageOrientationPatient.Count() > 5) { var imagePositionPatient = new ImagePositionPatient( segmentFrameData.ImagePositionPatient[0], segmentFrameData.ImagePositionPatient[1], segmentFrameData.ImagePositionPatient[2]); var imageOrientationPatient = new ImageOrientationPatient( segmentFrameData.ImageOrientationPatient[0], segmentFrameData.ImageOrientationPatient[1], segmentFrameData.ImageOrientationPatient[2], segmentFrameData.ImageOrientationPatient[3], segmentFrameData.ImageOrientationPatient[4], segmentFrameData.ImageOrientationPatient[5]); IDisplaySet displaySet = presentationImage.ParentDisplaySet; if (segPresentationImage == null) { segPresentationImage = PresentationImageFromPositionOrientation( imagePositionPatient, imageOrientationPatient, displaySet, segImageData.FrameOfReferenceUid); } var imageSop = segPresentationImage as IImageSopProvider; if (imageSop != null) { Vector3D segImageLocation = imageSop.Frame.ImagePlaneHelper.ConvertToImagePlane(new Vector3D( (float)imagePositionPatient.X, (float)imagePositionPatient.Y, (float)imagePositionPatient.Z)); PointF?segPixelLocation = imageSop.Frame.ImagePlaneHelper.ConvertToImage( new PointF(segImageLocation.X, segImageLocation.Y)); if (segPixelLocation.HasValue) { segLocation = segPixelLocation.Value; } } } if (segPresentationImage != null) { SegFrameImageGraphic newGraphic = AddSegFrameImageGraphicToPresentationImage( segPresentationImage, segImageData.Rows, segImageData.Columns, segLocation.X, segLocation.Y, seg.Color, referencedImageFrameNumber, seg.Label, seg.Description, pixelDataGetter.Invoke(segmentFrameData.FrameNumber - 1), new SegmentationDocumentReference(segmentationDocument, seg.SegmentationNumber)); if (newGraphic != null && segPresentationImage == segPresentationImage.ParentDisplaySet.ImageBox.TopLeftPresentationImage) { newGraphic.Draw(); } } else { Platform.Log(LogLevel.Error, "Failed to find Presentation Image to display a segment on"); } } }
//TODO: I should be able to replace this with the media readers now protected override WadoResponse DoProcess(IWadoUriRequest request, string mimeType) { var dcmLocation = MediaStorage.GetLocation(new DicomMediaId(request, MimeMediaTypes.DICOM)); //var dcmLocation = RetrieveService.RetrieveSopInstances ( request, mimeType ).FirstOrDefault(); if (!dcmLocation.Exists( )) { throw new ApplicationException("Object Not Found - return proper wado error "); } //if (string.Compare(mimeType, MimeMediaTypes.DICOM, true) == 0) { return(new WadoResponse(Location, mimeType)); } DicomFile file = new DicomFile( ); var frameIndex = request.ImageRequestInfo.FrameNumber - 1 ?? 0; frameIndex = Math.Max(frameIndex, 0); file.Load(dcmLocation.GetReadStream()); if (string.Compare(mimeType, MimeMediaTypes.Jpeg, true) == 0) { WadoResponse response = new WadoResponse(); if (file.TransferSyntax == TransferSyntax.JpegBaselineProcess1) { //ClearCanvas.Dicom.Codec.Jpeg.Jpeg8Codec codec = new ClearCanvas.Dicom.Codec.Jpeg.Jpeg8Codec (ClearCanvas.Dicom.Codec.Jpeg.JpegMode.Baseline, 0, 0 ) //codec.Encode () DicomCompressedPixelData pd = DicomPixelData.CreateFrom(file) as DicomCompressedPixelData; byte[] buffer = pd.GetFrameFragmentData(frameIndex); response.Content = new MemoryStream(buffer); response.MimeType = mimeType; return(response); } else { } } if (string.Compare(mimeType, MimeMediaTypes.UncompressedData) == 0) { WadoResponse response = null; DicomPixelData pd = null; byte[] buffer = null; response = new WadoResponse( ); pd = DicomPixelData.CreateFrom(file); buffer = pd.GetFrame(frameIndex); //********* TEST CODE*************** //System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap (pd.ImageWidth, pd.ImageHeight, System.Drawing.Imaging.PixelFormat.Format8bppIndexed ) ; //System.Drawing.Imaging.ColorPalette ncp = bitmap.Palette; // for (int i = 0; i < 256; i++) // ncp.Entries[i] = System.Drawing.Color.FromArgb(255, i, i, i); // bitmap.Palette = ncp; // System.Drawing.Imaging.BitmapData data = bitmap.LockBits (new System.Drawing.Rectangle ( 0,0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format8bppIndexed); //IntPtr ptr = data.Scan0 ; //System.Runtime.InteropServices.Marshal.Copy (buffer, 0, ptr, buffer.Length ) ; //string fileName = @"C:\Users\zalsafadi_p.SPX\Downloads\libwebp-master\Output\release-static\x86\bin\Samples\uncompressed.raw" ; //bitmap.UnlockBits (data); //bitmap.Save ( fileName); //File.WriteAllBytes(fileName, buffer) ; //********* TEST CODE*************** response.Content = new MemoryStream(buffer); response.MimeType = mimeType; return(response); } //if ( string.Compare(mimeType, MimeMediaTypes.WebP) == 0) //{ // WadoResponse response = new WadoResponse ( ) ; // byte[] buffer = File.ReadAllBytes(Location) ; // response.Content = new MemoryStream(buffer); // response.MimeType = mimeType ; // return response ; //} return(null); }