static void Main(string[] args) { try { // Read an explicitly typed image itkImageBase image = itkImage_F2.New(); image.Read(args[0]); // Create the interpolator InterpolatorType interp = InterpolatorType.New(image, CoordType.D); interp.SetInputImage(image); // Sample the image at a given physical location itkPoint point = new itkPoint(127.5, 127.5); itkPixel pixel = interp.Evaluate(point); Console.WriteLine(point.ToString() + "=" + pixel.ToString()); // Clean up image.Dispose(); interp.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } // end main
static void Main(string[] args) { try { // Create an explicit image type itkImageBase image = itkImage_SS3.New(); // Read the DICOM image from the given directory image.ReadDicomDirectory(args[0]); // Display some image information Console.WriteLine(String.Format("Name={0}",image.Name)); Console.WriteLine(String.Format("PixelType={0}",image.PixelType)); Console.WriteLine(String.Format("Dimension={0}",image.Dimension)); Console.WriteLine(String.Format("Size={0}",image.Size)); Console.WriteLine(String.Format("Spacing={0}",image.Spacing)); Console.WriteLine(String.Format("Origin={0}",image.Origin)); Console.WriteLine(String.Format("Buffer={0}",image.Buffer)); // Write the image to disk image.Write(args[1]); // Dispose of the image // Note: the image will be automatically disposed when it goes // out of scope, however it is good practice to dispose of // objects when they are no longer required. image.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } // end main
static void Main(String[] args) { try { // Setup input and output images UInt32 dim = UInt32.Parse(args[0]); itkImageBase input = itkImage.New(itkPixelType.F, dim); itkImageBase output = itkImage.New(itkPixelType.UC, dim); // Read the input image input.Read(args[1]); // Apply the Rescale Intensity filter FilterType filterRescale = FilterType.New(input, output); filterRescale.RemoveAllObservers(); filterRescale.SetInput(input); filterRescale.OutputMinimum = 000.0F; filterRescale.OutputMaximum = 255.0F; filterRescale.Update(); filterRescale.GetOutput(output); // Write the output to disk output.Write(args[2]); // Clean up filterRescale.Dispose(); input.Dispose(); output.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
static void Main(String[] args) { try { // Setup input and output images itkImageBase input = itkImage.New(args[0]); itkImageBase output = itkImage.New(input); // Read the input image input.Read(args[1]); // Apply the filter FilterType filter = FilterType.New(input, output); filter.SetInput(input); filter.Update(); filter.GetOutput(output); // Write the output to disk output.Write(args[2]); // Clean up filter.Dispose(); input.Dispose(); output.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } // end main
static void Main(String[] args) { try { // Create input and output images itkImageBase input = itkImage.New(args[0]); itkImageBase output = itkImage.New(input); // Read the input image input.Read(args[1]); // Apply the Sigmoid filter FilterType filter = FilterType.New(input, output); filter.Started += new itkEventHandler(filter_Started); filter.Progress += new itkProgressHandler(filter_Progress); filter.Ended += new itkEventHandler(filter_Ended); filter.SetInput(input); filter.GetOutput(output); filter.Alpha = Double.Parse(args[2]); filter.Beta = Double.Parse(args[3]); // Write the output to disk // NOTE: Any upstream filters will be automatically updated output.Write(args[4]); // Clean up filter.Dispose(); input.Dispose(); output.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
public static void CopyToItkImage(GrayscaleImageGraphic image, itkImageBase itkImage) { if (image.BitsPerPixel == 16) { if (image.IsSigned) { CopyToSigned16(image, itkImage); } else { CopyToUnsigned16(image, itkImage); } } else { if (image.IsSigned) { CopyToSigned8(image, itkImage); } else { CopyToUnsigned8(image, itkImage); } } }
static void Main(string[] args) { try { // Create an explicit image type itkImageBase image = itkImage_UC3.New(); // Read the image series using a pattern // Example: pattern = "Engine_*.png" image.ReadSeries(args[0], args[1]); // Display some image information Console.WriteLine(String.Format("PixelType={0}",image.PixelType)); Console.WriteLine(String.Format("Dimension={0}",image.Dimension)); Console.WriteLine(String.Format("Size={0}",image.Size)); Console.WriteLine(String.Format("Spacing={0}",image.Spacing)); Console.WriteLine(String.Format("Origin={0}",image.Origin)); Console.WriteLine(String.Format("Buffer={0}",image.Buffer)); // Write the image to disk as a series // Example: filenameFormat = "C:/temp/Engine2_{0}.jpg" // Example: seriesFormat = "0000" image.WriteSeries(args[2], args[3]); // Dispose of the image // Note: the image will be automatically disposed when it goes // out of scope, however it is good practice to dispose of // objects when they are no longer required. image.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } // end main
static void Main() { try { // In native ITK, images are templated over the pixel type // and number of dimensions. Templates are not supported by // the CLR, so therefore the creation of images with // ManagedITK is somewhat different. The wrapping process // creates two types of images: a number of explicit types // for various template combinations, and a wrapper type. // In this example we use an explicit type. // Create an image using an explicit type // Note: "UC2" stands for itk::Image< unsigned char, 2 >. itkImageBase image = itkImage_UC2.New(); // Create some image information itkSize size = new itkSize(128, 128); itkSpacing spacing = new itkSpacing(1.0, 1.0); itkIndex index = new itkIndex(0, 0); itkPoint origin = new itkPoint(0.0, 0.0); itkImageRegion region = new itkImageRegion(size, index); // Set the information // Note: we must call SetRegions() *before* calling Allocate(). image.SetRegions(region); image.Allocate(); image.Spacing = spacing; image.Origin = origin; // Fill the image with gray (ie. 128) image.FillBuffer(128); // Test a pixel value itkPixel pixel = image.GetPixel(index); // Display some image information Console.WriteLine(String.Format("Image{0}={1}",index, pixel)); Console.WriteLine(String.Format("PixelType={0}",image.PixelType)); Console.WriteLine(String.Format("Dimension={0}",image.Dimension)); Console.WriteLine(String.Format("Size={0}",image.Size)); Console.WriteLine(String.Format("Spacing={0}",image.Spacing)); Console.WriteLine(String.Format("Origin={0}",image.Origin)); Console.WriteLine("======================================"); Console.WriteLine("Image.ToString():"); Console.WriteLine(image); // Dispose of the image // Note: the image will be automatically disposed when it goes // out of scope, however it is good practice to dispose of // objects when they are no longer required. image.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } // end main
public void Start() { itkImageBase imIn = Filters.ImageIO.ReadImage(filenameIn); imOut = itkImage_UC2.New(); Filters.GradientMagnitudeFilter gmf= new Filters.GradientMagnitudeFilter(); gmf.Run(imIn, ref imOut); filenameOut = "C:\\EmbryoSegmenter_Temp\\" + Guid.NewGuid() + ".bmp"; //imOut.Write(filenameOut); imIn.Dispose(); //imOut.Dispose(); }
public void Apply() { if (this.SelectedImageGraphicProvider == null) { return; } ImageGraphic image = this.SelectedImageGraphicProvider.ImageGraphic; if (image == null) { return; } if (!(image is GrayscaleImageGraphic)) { return; } itkImageBase input = ItkHelper.CreateItkImage(image as GrayscaleImageGraphic); itkImageBase output = itkImage.New(input); ItkHelper.CopyToItkImage(image as GrayscaleImageGraphic, input); FilterType filter = FilterType.New(input, output); filter.SetInput(input); String mangledType = input.MangledTypeString; intensityFilterType intensityFilter = intensityFilterType.New(mangledType + mangledType); intensityFilter.SetInput(filter.GetOutput()); intensityFilter.OutputMinimum = 0; if (image.BitsPerPixel == 16) { intensityFilter.OutputMaximum = 32767; } else { intensityFilter.OutputMaximum = 255; } intensityFilter.Update(); intensityFilter.GetOutput(output); ItkHelper.CopyFromItkImage(image as GrayscaleImageGraphic, output); image.Draw(); filter.Dispose(); intensityFilter.Dispose(); input.Dispose(); output.Dispose(); }
static void Main(string[] args) { try { // Create a managed array to import const Int32 Width = 256; const Int32 Height = 256; List<float> list = new List<float>(Width * Height); for (int j = 0; j < Height; j++) { for (int i = 0; i < Width; i++) { if (i == j) list.Add(Convert.ToSingle(i)); else list.Add(0.0F); } } // Pin the managed array for use with unmanaged code float[] array = list.ToArray(); GCHandle handle = GCHandle.Alloc(array, GCHandleType.Pinned); // Setup for import itkImportImageFilter_F2 importer = itkImportImageFilter_F2.New(); itkSize size = new itkSize(Width, Height); itkIndex index = new itkIndex(0, 0); importer.Region = new itkImageRegion(size, index); importer.Spacing = new itkSpacing(1.0, 1.0); importer.Origin = new itkPoint(0.0, 0.0); importer.SetImportPointer(handle.AddrOfPinnedObject(), (uint)list.Count, false); // Perform import itkImageBase output = itkImage_F2.New(); importer.UpdateLargestPossibleRegion(); importer.GetOutput(output); output.Write(args[0]); // Display some image information Console.WriteLine(String.Format("{0}", output)); // Cleanup output.Dispose(); importer.Dispose(); handle.Free(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } // end main
static void Main(string[] args) { try { // The itkImageBase.ReadInformation() method can be used to // "sniff" out the image information stored in the file. // Read the image file information itkImageInformation info = itkImageBase.ReadInformation(args[0]); // Display the IO information Console.WriteLine("Information --------------------------"); Console.WriteLine(String.Format("PixelType={0}",info.PixelType)); Console.WriteLine(String.Format("Dimension={0}",info.Dimension)); Console.WriteLine(String.Format("Size={0}",info.Size)); Console.WriteLine(String.Format("Spacing={0}",info.Spacing)); Console.WriteLine(String.Format("Origin={0}",info.Origin)); // Use file information to create and read an image itkImageBase image = itkImage.New(info.PixelType, info.Dimension); image.Read(args[0]); // Display some image information Console.WriteLine("Image --------------------------------"); Console.WriteLine(String.Format("Name={0}",image.Name)); Console.WriteLine(String.Format("PixelType={0}",image.PixelType)); Console.WriteLine(String.Format("Dimension={0}",image.Dimension)); Console.WriteLine(String.Format("Size={0}",image.Size)); Console.WriteLine(String.Format("Spacing={0}",image.Spacing)); Console.WriteLine(String.Format("Origin={0}",image.Origin)); Console.WriteLine(String.Format("Buffer={0}",image.Buffer)); // Dispose of the image // Note: the image will be automatically disposed when it goes // out of scope, however it is good practice to dispose of // objects when they are no longer required. image.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } // end main
public bool OpenDicomFile(string fname) { this.m_Image = itkImage_UC2.New(); this.m_Image.Read(fname); try { // Convert the image to a Bitmap and display bmp = this.ConvertItkImageToBitmap(this.m_Image); return(true); } catch (NotSupportedException ex) { String text = ex.ToString(); String caption = "Image type not supported"; MessageBox.Show(text, caption, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(false); } }
static void Main(string[] args) { try { // Read an explicitly typed image itkImageBase input = itkImage_UC2.New(); input.Read(args[0]); // Allocate an empty output image itkImageBase output = itkImage_UC2.New(); itkImageRegion region = input.LargestPossibleRegion; output.SetRegions(region); output.Allocate(); output.FillBuffer(0); output.Spacing = input.Spacing; output.Origin = input.Origin; // Create iterators to walk the input and output images itkImageRegionConstIterator_IUC2 inputIt; itkImageRegionIterator_IUC2 outputIt; inputIt = new itkImageRegionConstIterator_IUC2(input, region); outputIt = new itkImageRegionIterator_IUC2(output, region); // Walk the images using the iterators foreach (itkPixel pixel in inputIt) { outputIt.Set(pixel); outputIt++; } // Write the output image output.Write(args[1]); // Dispose of the images input.Dispose(); output.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } // end main
private unsafe static void CopyFromUnsigned8(ImageGraphic image, itkImageBase itkImage) { fixed(byte *pDstByte = image.PixelData.Raw) { itkImageRegionConstIterator_IUC2 itkIt = new itkImageRegionConstIterator_IUC2(itkImage, itkImage.LargestPossibleRegion); byte *pDst = (byte *)pDstByte; int height = image.Rows; int width = image.Columns; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { pDst[0] = itkIt.Get().ValueAsUC; pDst++; itkIt++; } } } }
/// <summary> /// Default constructor. /// </summary> /// <param name="filename">The filename of the image to display.</param> public FormBitmap1(String filename) { // Init the GUI InitializeComponent(); // Read the image this.m_Image = itkImage_UC2.New(); this.m_Image.Read(filename); try { // Convert the image to a Bitmap and display this.pictureImage.Image = this.ConvertItkImageToBitmap(this.m_Image); } catch (NotSupportedException ex) { String text = ex.ToString(); String caption = "Image type not supported"; MessageBox.Show(this, text, caption, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
static void Main(string[] args) { try { // Create the initial, feature and output images itkPixelType pixeltype = itkPixelType.F; uint Dimension = UInt32.Parse(args[0]); itkImageBase initial = itkImage.New(pixeltype, Dimension); itkImageBase speed = itkImage.New(pixeltype, Dimension); itkImageBase output = itkImage.New(pixeltype, Dimension); Console.WriteLine("Reading initial: " + args[1]); initial.Read(args[1]); Console.WriteLine("Reading speed: " + args[2]); speed.Read(args[2]); // Level Set LevelSetType levelset = LevelSetType.New(initial, speed, pixeltype); levelset.Started += new itkEventHandler(LevelSetStarted); levelset.Iteration += new itkEventHandler(LevelSetIteration); levelset.Ended += new itkEventHandler(LevelSetEnded); levelset.SetInitialImage(initial); levelset.SetFeatureImage(speed); levelset.PropagationScaling = 5.0; levelset.CurvatureScaling = 3.0; levelset.AdvectionScaling = 1.0; levelset.MaximumRMSError = 0.01; levelset.NumberOfIterations = 600; levelset.Update(); levelset.GetOutput(output); // Write the output image to disk Console.WriteLine("Writing output: " + args[3]); output.Write(args[3]); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
static void Main(string[] args) { try { // Setup typedefs itkPixelType pixel = itkPixelType.D; itkDimension dim = new itkDimension(3); itkMeshTraits traits = itkMeshTraits.Static(); // Create mesh itkMesh mesh = itkMesh.New(pixel, dim, traits); itkRegularSphereMeshSource source = itkRegularSphereMeshSource.New(mesh); source.Center = new itkPoint(32.0, 32.0, 32.0); source.Scale = new itkVector(32.0, 32.0, 32.0); source.Resolution = 4; source.Update(); source.GetOutput(mesh); // Convert mesh to image itkImageBase output = itkImage.New(itkPixelType.UC, dim.Dimension); itkTriangleMeshToBinaryImageFilter filter = itkTriangleMeshToBinaryImageFilter.New(mesh, output); filter.SetInput(mesh); filter.Tolerance = 0.001; filter.Size = new itkSize(100, 100, 100); filter.Update(); filter.GetOutput(output); output.Write(args[0]); // Cleanup filter.Dispose(); output.Dispose(); mesh.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } // end main
public void Apply() { if (this.SelectedImageGraphicProvider == null) { return; } ImageGraphic image = this.SelectedImageGraphicProvider.ImageGraphic; if (image == null) { return; } if (!(image is GrayscaleImageGraphic)) { return; } itkImageBase input = ItkHelper.CreateItkImage(image as GrayscaleImageGraphic); itkImageBase output = itkImage.New(input); ItkHelper.CopyToItkImage(image as GrayscaleImageGraphic, input); FilterType filter = FilterType.New(input, output); filter.SetInput(input); filter.Update(); filter.GetOutput(output); ItkHelper.CopyFromItkImage(image as GrayscaleImageGraphic, output); image.Draw(); filter.Dispose(); input.Dispose(); output.Dispose(); }
private unsafe static void CopyToUnsigned8(ImageGraphic image, itkImageBase itkImage) { fixed(byte *pSrcByte = image.PixelData.Raw) { itkImageRegionIterator_IUC2 inputIt = new itkImageRegionIterator_IUC2(itkImage, itkImage.LargestPossibleRegion); byte *pSrc = (byte *)pSrcByte; int height = image.Rows; int width = image.Columns; byte pixelValue; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { pixelValue = pSrc[0]; inputIt.Set(pixelValue); pSrc++; inputIt++; } } } }
static void Main(string[] args) { try { // One of the benefits of ManagedITK is the ability to easily // choose the image type at run-time, rather than compile-time. // Use the image type from the command line to create an image itkImageBase image = itkImage.New(args[0]); // Read the image from disk image.Read(args[1]); // Display some image information Console.WriteLine(String.Format("Name={0}",image.Name)); Console.WriteLine(String.Format("PixelType={0}",image.PixelType)); Console.WriteLine(String.Format("Dimension={0}",image.Dimension)); Console.WriteLine(String.Format("Size={0}",image.Size)); Console.WriteLine(String.Format("Spacing={0}",image.Spacing)); Console.WriteLine(String.Format("Origin={0}",image.Origin)); Console.WriteLine(String.Format("Buffer={0}",image.Buffer)); // Write the image to disk image.Write(args[2]); // Dispose of the image // Note: the image will be automatically disposed when it goes // out of scope, however it is good practice to dispose of // objects when they are no longer required. image.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } // end main
public void Apply() { if (this.SelectedImageGraphicProvider == null) { return; } ImageGraphic image = this.SelectedImageGraphicProvider.ImageGraphic; if (image == null) { return; } if (!(image is GrayscaleImageGraphic)) { return; } itkImageBase input = ItkHelper.CreateItkImage(image as GrayscaleImageGraphic); itkImageBase output = itkImage.New(input); ItkHelper.CopyToItkImage(image as GrayscaleImageGraphic, input); String mangledType = input.MangledTypeString; CastImageFilterType castToIF2 = CastImageFilterType.New(mangledType + "IF2"); SmoothingFilterType smoothingFilter = SmoothingFilterType.New("IF2IF2"); smoothingFilter.TimeStep = 0.125; smoothingFilter.NumberOfIterations = 5; smoothingFilter.ConductanceParameter = 9.0; GradientMagnitudeFilterType gradientMagnitudeFilter = GradientMagnitudeFilterType.New("IF2IF2"); gradientMagnitudeFilter.Sigma = 1.0; SigmoidFilterType sigmoidFilter = SigmoidFilterType.New("IF2IF2"); sigmoidFilter.OutputMinimum = 0.0; sigmoidFilter.OutputMaximum = 1.0; sigmoidFilter.Alpha = -0.5; //-0.3 sigmoidFilter.Beta = 3.0; //2.0 FastMarchingFilterType fastMarchingFilter = FastMarchingFilterType.New("IF2IF2"); double seedValue = 0.0; int[] seedPosition = { 256, 256 };// user input itkIndex seedIndex = new itkIndex(seedPosition); itkLevelSetNode[] trialPoints = { new itkLevelSetNode(seedValue, seedIndex) }; fastMarchingFilter.TrialPoints = trialPoints; fastMarchingFilter.StoppingValue = 100; BinaryThresholdFilterType binaryThresholdFilter = BinaryThresholdFilterType.New("IF2" + mangledType); //to UC2? binaryThresholdFilter.UpperThreshold = 100.0; //200 binaryThresholdFilter.LowerThreshold = 0.0; binaryThresholdFilter.OutsideValue = 0; if (image.BitsPerPixel == 16) { binaryThresholdFilter.InsideValue = (image as GrayscaleImageGraphic).ModalityLut.MaxInputValue;//32767; } else { binaryThresholdFilter.InsideValue = 255; } //intensityFilterType intensityFilter = intensityFilterType.New("UC2" + mangledType); //intensityFilter.OutputMinimum = 0; //if (image.BitsPerPixel == 16) // intensityFilter.OutputMaximum = (image as GrayscaleImageGraphic).ModalityLut.MaxInputValue;//32767; //else // intensityFilter.OutputMaximum = 255; // Make data stream connections castToIF2.SetInput(input); smoothingFilter.SetInput(castToIF2.GetOutput()); gradientMagnitudeFilter.SetInput(smoothingFilter.GetOutput()); sigmoidFilter.SetInput(gradientMagnitudeFilter.GetOutput()); fastMarchingFilter.SetInput(sigmoidFilter.GetOutput()); binaryThresholdFilter.SetInput(fastMarchingFilter.GetOutput()); //intensityFilter.SetInput(binaryThresholdFilter.GetOutput()); //smoothingFilter.Update(); fastMarchingFilter.OutputSize = input.BufferedRegion.Size;//? binaryThresholdFilter.Update(); binaryThresholdFilter.GetOutput(output); ItkHelper.CopyFromItkImage(image as GrayscaleImageGraphic, output); image.Draw(); input.Dispose(); output.Dispose(); }
/// <summary> /// Converts an itkImageBase to a System.Drawing.Bitmap. /// The itkImageBase must be a 2D image with scalar pixel type /// and UnsignedChar component type. A NotSupportedException /// is raised if the image does not meet these criteria. /// </summary> /// <param name="image">The image to convert</param> /// <returns></returns> public static Bitmap ConvertItkImageToBitmap(itkImageBase image) { // Check image is 2D if (image.Dimension != 2) { String message = String.Empty; message += "We can only display images with 2 dimensions."; message += "The given image has {0} dimensions!"; throw new NotSupportedException(String.Format(message, image.Dimension)); } // Check the pixel type is scalar if (!image.PixelType.IsScalar) { String message = "We can only display images with scalar pixels."; message += "The given image has {0} pixel type!"; throw new NotSupportedException(String.Format(message, image.PixelType)); } // Check the pixel type is unsigned char if (image.PixelType.TypeAsEnum != itkPixelTypeEnum.UnsignedChar) { String message = String.Empty; message += "We can only display images with UnsignedChar pixels."; message += "The given image has {0} pixel type!"; throw new NotSupportedException(String.Format(message, image.PixelType)); } // The result will be a System.Drawing.Bitmap Bitmap bitmap; // Set pixel format as 8-bit grayscale PixelFormat format = PixelFormat.Format8bppIndexed; // Check if the stride is the same as the width if (image.Size[0] % 4 == 0) { // Width = Stride: simply use the Bitmap constructor bitmap = new Bitmap(image.Size[0], // Width image.Size[1], // Height image.Size[0], // Stride format, // PixelFormat image.Buffer // Buffer ); } else { unsafe { // Width != Stride: copy data from buffer to bitmap int width = image.Size[0]; int height = image.Size[1]; byte* buffer = (byte*)image.Buffer.ToPointer(); // Compute the stride int stride = width; if (width % 4 != 0) stride = ((width / 4) * 4 + 4); bitmap = new Bitmap(width, height, format); Rectangle rect = new Rectangle(0, 0, width, height); BitmapData bitmapData = bitmap.LockBits(rect, ImageLockMode.WriteOnly, format); for (int j = 0; j < height; j++) // Row { byte* row = (byte*)bitmapData.Scan0 + (j * stride); for (int i = 0; i < width; i++) // Column row[i] = buffer[(j * width) + i]; } bitmap.UnlockBits(bitmapData); }// end unsafe }// end if (Width == Stride) // Set a color palette bitmap.Palette = CreateGrayscalePalette(format, 256); // Return the resulting bitmap return bitmap; }// end ConvertItkImageToBitmap()
public virtual void Run(itkImageBase imIn, ref itkImageBase imOut) { }
static void Main(string[] args) { try { // Setup typedefs itkPixelType pixel = itkPixelType.D; itkDimension dim = new itkDimension(3); itkMeshTraits traits = itkMeshTraits.Static(); // Compute gradient Console.WriteLine("Reading gradient: " + args[0]); itkImageBase gradient = itkImage_CVD33.New(); gradient.Read(args[0]); // Create initial mesh Console.WriteLine("Creating initial mesh"); itkMesh meshIn = itkMesh.New(pixel, dim, traits); itkRegularSphereMeshSource source = itkRegularSphereMeshSource.New(meshIn); source.Center = new itkPoint(20.0, 20.0, 20.0); source.Scale = new itkVector(5.0, 5.0, 5.0); source.Resolution = 4; source.Update(); source.GetOutput(meshIn); meshIn.DisconnectPipeline(); // Convert triangle mesh to simplex mesh Console.WriteLine("Converting triangle mesh to simplex mesh"); itkSimplexMesh simplexIn = itkSimplexMesh.New(pixel, dim, traits); itkTriangleMeshToSimplexMeshFilter convertToSimplex = itkTriangleMeshToSimplexMeshFilter.New(meshIn, simplexIn); convertToSimplex.SetInput(meshIn); convertToSimplex.Update(); convertToSimplex.GetOutput(simplexIn); simplexIn.DisconnectPipeline(); // Deform the simplex mesh Console.WriteLine("Deforming simplex mesh"); itkSimplexMesh simplexOut = itkSimplexMesh.New(pixel, dim, traits); itkDeformableSimplexMesh3DBalloonForceFilter deform = itkDeformableSimplexMesh3DBalloonForceFilter.New(simplexIn, simplexOut); deform.Alpha = 0.8; // Internal force scaling deform.Beta = 0.8; // External force scaling deform.Gamma = 0.1; // Reference metric scaling deform.Rigidity = 3; // Mesh smoothness (0=high curvature, 9=smooth) deform.Kappa = 0.1; // Internal balloon force scaling deform.Iterations = 200; deform.SetGradient(gradient); deform.SetInput(simplexIn); deform.Progress += new itkProgressHandler(FilterProgress); deform.Update(); deform.GetOutput(simplexOut); simplexOut.DisconnectPipeline(); Console.WriteLine(); // Convert simplex mesh to triangle mesh Console.WriteLine("Converting simplex mesh to triangle mesh"); itkMesh meshOut = itkMesh.New(pixel, dim, traits); itkSimplexMeshToTriangleMeshFilter convertToTriangle = itkSimplexMeshToTriangleMeshFilter.New(simplexOut, meshOut); convertToTriangle.SetInput(simplexOut); convertToTriangle.Update(); convertToTriangle.GetOutput(meshOut); meshOut.DisconnectPipeline(); // Convert mesh to image Console.WriteLine("Converting mesh to image: " + Path.GetFileName(args[1])); itkImageBase output = itkImage_UC3.New(); itkTriangleMeshToBinaryImageFilter filter = itkTriangleMeshToBinaryImageFilter.New(meshOut, output); filter.SetInput(meshOut); filter.Tolerance = 0.001; filter.Size = gradient.Size; filter.Spacing = gradient.Spacing; filter.Origin = gradient.Origin; filter.GetOutput(output); filter.Update(); output.Write(args[1]); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
public void Apply() { if (this.SelectedImageGraphicProvider == null) { return; } ImageGraphic image = this.SelectedImageGraphicProvider.ImageGraphic; if (image == null) { return; } if (!(image is GrayscaleImageGraphic)) { return; } byte[] pixels = image.PixelData.Raw; itkImageBase input = ItkHelper.CreateItkImage(image as GrayscaleImageGraphic); itkImageRegion region = input.LargestPossibleRegion; itkImageBase output = itkImage.New(input); ItkHelper.CopyToItkImage(image as GrayscaleImageGraphic, input); string mangledType = input.MangledTypeString; string mangledType2 = input.PixelType.MangledTypeString; CastImageFilterType castToIF2 = CastImageFilterType.New(mangledType + "IF2"); castToIF2.SetInput(input); FilterType filter = FilterType.New("IF2IF2"); filter.SetInput(castToIF2.GetOutput()); intensityFilterType intensityFilter = intensityFilterType.New("IF2" + mangledType); intensityFilter.SetInput(filter.GetOutput()); intensityFilter.OutputMinimum = 0; if (image.BitsPerPixel == 16) { intensityFilter.OutputMaximum = (image as GrayscaleImageGraphic).ModalityLut.MaxInputValue; } else { intensityFilter.OutputMaximum = 255; } intensityFilter.Update(); intensityFilter.GetOutput(output); ItkHelper.CopyFromItkImage(image as GrayscaleImageGraphic, output); image.Draw(); filter.Dispose(); intensityFilter.Dispose(); input.Dispose(); output.Dispose(); }
public void Apply() { if (this.SelectedImageGraphicProvider == null) { return; } ImageGraphic image = this.SelectedImageGraphicProvider.ImageGraphic; if (image == null) { return; } if (!(image is GrayscaleImageGraphic)) { return; } itkImageBase input = ItkHelper.CreateItkImage(image as GrayscaleImageGraphic); itkImageBase output = itkImage.New(input); ItkHelper.CopyToItkImage(image as GrayscaleImageGraphic, input); FilterType filter = FilterType.New(input, output); bool abc = false; if (abc) { byte[] pixels = image.PixelData.Raw; unsafe { byte[] dummy = new byte[512 * 512]; IntPtr bptr = input.Buffer; void * pbptr = bptr.ToPointer(); { filter.SetInput(bptr); } fixed(byte *dummyAddr = &dummy[0]) { *dummyAddr = 1; *(dummyAddr + 1) = 2; IntPtr ptr = new IntPtr(dummyAddr); filter.SetInput(ptr); } fixed(byte *pByte = image.PixelData.Raw) { IntPtr x = new IntPtr((void *)pByte); void * p = x.ToPointer(); filter.SetInput(x);//runtime memory protected exception because it expects x.ToPointer() is ITK::Image_XX* (see implementation of MITK) } } } else { filter.SetInput(input); } filter.NormalizeAcrossScale = false; filter.Sigma = 3; filter.Update(); filter.GetOutput(output); filter.GetOutput(output); ItkHelper.CopyFromItkImage(image as GrayscaleImageGraphic, output); image.Draw(); filter.Dispose(); input.Dispose(); output.Dispose(); }
private unsafe static void CopyToUnsigned8(ImageGraphic image, itkImageBase itkImage) { fixed (byte* pSrcByte = image.PixelData.Raw) { itkImageRegionIterator_IUC2 inputIt = new itkImageRegionIterator_IUC2(itkImage, itkImage.LargestPossibleRegion); byte* pSrc = (byte*)pSrcByte; int height = image.Rows; int width = image.Columns; byte pixelValue; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { pixelValue = pSrc[0]; inputIt.Set(pixelValue); pSrc++; inputIt++; } } } }
private unsafe static void CopyFromUnsigned8(ImageGraphic image, itkImageBase itkImage) { fixed (byte* pDstByte = image.PixelData.Raw) { itkImageRegionConstIterator_IUC2 itkIt = new itkImageRegionConstIterator_IUC2(itkImage, itkImage.LargestPossibleRegion); byte* pDst = (byte*)pDstByte; int height = image.Rows; int width = image.Columns; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { pDst[0] = itkIt.Get().ValueAsUC; pDst++; itkIt++; } } } }
public void Apply() { if (this.SelectedImageGraphicProvider == null) { return; } ImageGraphic image = this.SelectedImageGraphicProvider.ImageGraphic; if (image == null) { return; } if (!(image is GrayscaleImageGraphic)) { return; } byte[] pixels = image.PixelData.Raw; itkImageBase input = ItkHelper.CreateItkImage(image as GrayscaleImageGraphic); itkImageRegion region = input.LargestPossibleRegion; itkImageBase output = itkImage.New(input); ItkHelper.CopyToItkImage(image as GrayscaleImageGraphic, input); String mangledType = input.MangledTypeString; CastImageFilterType castToIF2 = CastImageFilterType.New(mangledType + "IF2"); castToIF2.SetInput(input); FilterType filter = FilterType.New("IF2IF2"); filter.SetInput(castToIF2.GetOutput()); // TODO: need to allow user to set parameters of filter filter.LowerThreshold = 90; filter.UpperThreshold = 127; //filter.OutsideValue = 0; // smoothing the edge double[] error = { 0.01, 0.01 }; filter.MaximumError = error; double[] var = { 1.0, 1.0 }; filter.Variance = var; intensityFilterType intensityFilter = intensityFilterType.New("IF2" + mangledType); intensityFilter.SetInput(filter.GetOutput()); intensityFilter.OutputMinimum = 0; if (image.BitsPerPixel == 16) { intensityFilter.OutputMaximum = (image as GrayscaleImageGraphic).ModalityLut.MaxInputValue;//32767; } else { intensityFilter.OutputMaximum = 255; } intensityFilter.Update(); #if DEBUG bool debug = false; if (debug) { itkImageBase outputIF2 = itkImage.New("IF2"); filter.GetOutput(outputIF2); float min = float.MaxValue, max = float.MinValue; unsafe { fixed(byte *pDstByte = image.PixelData.Raw) { itkImageRegionConstIterator_IF2 itkIt = new itkImageRegionConstIterator_IF2(outputIF2, region); byte *pDst = (byte *)pDstByte; int height = image.Rows; int width = image.Columns; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { float f = itkIt.Get().ValueAsF; if (f > max) { max = f; } if (f < min) { min = f; } pDst[0] = (byte)itkIt.Get().ValueAsF; pDst++; itkIt++; } } } } Console.WriteLine("min max "); Console.Write(min); Console.Write(" "); Console.WriteLine(max); } #endif intensityFilter.GetOutput(output); ItkHelper.CopyFromItkImage(image as GrayscaleImageGraphic, output); image.Draw(); filter.Dispose(); intensityFilter.Dispose(); input.Dispose(); output.Dispose(); }
public override void Run(itkImageBase imIn, ref itkImageBase imOut) { }
/// <summary> /// Converts an itkImageBase to a System.Drawing.Bitmap. /// The itkImageBase must be a 2D image with scalar pixel type /// and UnsignedChar component type. A NotSupportedException /// is raised if the image does not meet these criteria. /// </summary> /// <param name="image">The image to convert</param> /// <returns></returns> private Bitmap ConvertItkImageToBitmap(itkImageBase image) { // Check image is 2D if (image.Dimension != 2) { String message = String.Empty; message += "We can only display images with 2 dimensions."; message += "The given image has {0} dimensions!"; throw new NotSupportedException(String.Format(message, image.Dimension)); } // Check the pixel type is scalar if (!image.PixelType.IsScalar) { String message = "We can only display images with scalar pixels."; message += "The given image has {0} pixel type!"; throw new NotSupportedException(String.Format(message, image.PixelType)); } // Check the pixel type is unsigned char if (image.PixelType.TypeAsEnum != itkPixelTypeEnum.UnsignedChar) { String message = String.Empty; message += "We can only display images with UnsignedChar pixels."; message += "The given image has {0} pixel type!"; throw new NotSupportedException(String.Format(message, image.PixelType)); } // The result will be a System.Drawing.Bitmap Bitmap bitmap; // Set pixel format as 8-bit grayscale PixelFormat format = PixelFormat.Format8bppIndexed; // Check if the stride is the same as the width if (image.Size[0] % 4 == 0) { // Width = Stride: simply use the Bitmap constructor bitmap = new Bitmap(image.Size[0], // Width image.Size[1], // Height image.Size[0], // Stride format, // PixelFormat image.Buffer // Buffer ); } else { unsafe { // Width != Stride: copy data from buffer to bitmap int width = image.Size[0]; int height = image.Size[1]; byte *buffer = (byte *)image.Buffer.ToPointer(); // Compute the stride int stride = width; if (width % 4 != 0) { stride = ((width / 4) * 4 + 4); } bitmap = new Bitmap(width, height, format); Rectangle rect = new Rectangle(0, 0, width, height); BitmapData bitmapData = bitmap.LockBits(rect, ImageLockMode.WriteOnly, format); for (int j = 0; j < height; j++) // Row { byte *row = (byte *)bitmapData.Scan0 + (j * stride); for (int i = 0; i < width; i++) // Column { row[i] = buffer[(j * width) + i]; } } bitmap.UnlockBits(bitmapData); } // end unsafe } // end if (Width == Stride) // Set a color palette bitmap.Palette = this.CreateGrayscalePalette(format, 256); // Return the resulting bitmap return(bitmap); }// end ConvertItkImageToBitmap()
static void Main(string[] args) { try { // Read the fixed image from the command line itkImageBase imageFixed = ImageType.New(); imageFixed.Read(args[0]); // Create a moving image itkImageBase imageMoving = itkImage.New(imageFixed); // Create the interpolator InterpolatorType interpolator = InterpolatorType.New(); // Create the transform TransformType transform = TransformType.New(); transform.Translate(new itkVector(7.5, 12.0)); Console.WriteLine("START: " + transform.Parameters.ToString()); // Make the moving image by resampling the fixed image // with known parameters ResampleType filterResample = ResampleType.New(); filterResample.SetInput(imageFixed); filterResample.SetInterpolator(interpolator); filterResample.SetTransform(transform); filterResample.OutputSize = imageFixed.Size; filterResample.OutputSpacing = imageFixed.Spacing; filterResample.Update(); filterResample.GetOutput(imageMoving); imageMoving.DisconnectPipeline(); imageFixed.DisconnectPipeline(); // Write out the fixed and moving images imageFixed.Write(AddSuffixToFileName(args[0], "_FIXED")); imageMoving.Write(AddSuffixToFileName(args[0], "_MOVING")); // Reset the transform initial parameters transform.Translate(new itkVector(0.0, 0.0)); // Create metric MetricType metric = MetricType.New(); // Create optimiser OptimizerType optimizer = OptimizerType.New(); optimizer.Iteration += new itkEventHandler(optimizer_Iteration); optimizer.MaximumStepLength = 4.00; optimizer.MinimumStepLength = 0.01; optimizer.NumberOfIterations = 200; // Create registration method RegistrationType registration = RegistrationType.New(); registration.SetFixedImage(imageFixed); registration.SetMovingImage(imageMoving); registration.SetTransform(transform); registration.SetInterpolator(interpolator); registration.SetMetric(metric); registration.SetOptimizer(optimizer); registration.InitialTransformParameters = transform.Parameters; registration.StartRegistration(); // Rotate the moving image with the found parameters filterResample.SetInput(imageMoving); filterResample.SetInterpolator(interpolator); filterResample.SetTransform(transform); filterResample.OutputSize = imageMoving.Size; filterResample.OutputSpacing = imageMoving.Spacing; filterResample.Update(); filterResample.GetOutput(imageMoving); imageMoving.DisconnectPipeline(); // Write out the results Console.WriteLine("END: " + transform.Parameters.ToString()); imageMoving.Write(AddSuffixToFileName(args[0], "_REGISTERED")); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }