/// <summary> /// Update the 2D visualization when the plane moved. /// </summary> /// <param name="plane">PlaneWidget which changed the coordinates.</param> public void PlaneMoved(vtkImagePlaneWidget plane) { vtkImageReslice reslice = vtkImageReslice.New(); vtkTransform transform = vtkTransform.New(); transform.PostMultiply(); //TODO wyznaczenie centrum okna double[] center = { 75, 100, 0 }; transform.Translate(-center[0], -center[1], -center[2]); transform.RotateZ(_orientation); transform.Translate(+center[0], +center[1], +center[2]); transform.Update(); reslice.SetInput(plane.GetResliceOutput()); reslice.SetResliceTransform(transform); reslice.Update(); // vtkImageData viewerInputData; viewerInputData = reslice.GetOutput(); _lastData = viewerInputData; _viewer.SetInput(viewerInputData); // //_viewer.SetInput(reslice.GetOutput()); UpdateViewer(); }
private vtkImageData CreateVtkVolume() { vtkImageData vtkVolume = new vtkImageData(); VtkHelper.RegisterVtkErrorEvents(vtkVolume); vtkVolume.SetDimensions(ArrayDimensions.Width, ArrayDimensions.Height, ArrayDimensions.Depth); vtkVolume.SetOrigin(Origin.X, Origin.Y, Origin.Z); vtkVolume.SetSpacing(VoxelSpacing.X, VoxelSpacing.Y, VoxelSpacing.Z); if (!this.Signed) { vtkVolume.SetScalarTypeToUnsignedShort(); vtkVolume.GetPointData().SetScalars( VtkHelper.ConvertToVtkUnsignedShortArray(_volumeDataUInt16)); } else { vtkVolume.SetScalarTypeToShort(); vtkVolume.GetPointData().SetScalars( VtkHelper.ConvertToVtkShortArray(_volumeDataInt16)); } // This call is necessary to ensure vtkImageData data's info is correct (e.g. updates WholeExtent values) vtkVolume.UpdateInformation(); return(vtkVolume); }
/// <summary> /// Initializes a new instance of the <see cref="VtkImageDataHandle"/> class with the <see cref="vtkImageData"/> to wrap and /// a <see cref="GCHandleType.Pinned"/> <see cref="GCHandle"/> to the managed data array to be used by VTK. /// </summary> /// <remarks> /// When this <see cref="VtkImageDataHandle"/> is disposed, both the <paramref name="vtkImageData"/> and /// the <paramref name="pinningHandle"/> will be released. /// </remarks> /// <param name="vtkImageData">The <see cref="vtk.vtkImageData"/> object holding the handle to a managed data array.</param> /// <param name="pinningHandle">A <see cref="GCHandle"/> pinning the managed data array.</param> public VtkImageDataHandle(vtkImageData vtkImageData, GCHandle pinningHandle) { Platform.CheckForNullReference(vtkImageData, "vtkImageData"); _vtkImageData = vtkImageData; _pinningHandle = pinningHandle; }
/// <summary> /// Call to obtain a VTK volume structure that is safe for VTK to operate on. When done /// operating on the volume, call <see cref="ReleasePinnedVtkVolume"/>. /// </summary> /// <returns></returns> internal vtkImageData ObtainPinnedVtkVolume() { //TODO: Wrap with disposable object and have released on Dispose // Create the VTK volume wrapper if it doesn't exist if (_cachedVtkVolume == null) { _cachedVtkVolume = CreateVtkVolume(); } // Pin the managed volume array. If not null, then already pinned so we do not re-pin. if (_volumeArrayPinnedHandle == null) { if (!this.Signed) { _volumeArrayPinnedHandle = GCHandle.Alloc(_volumeDataUInt16, GCHandleType.Pinned); } else { _volumeArrayPinnedHandle = GCHandle.Alloc(_volumeDataInt16, GCHandleType.Pinned); } } return(_cachedVtkVolume); }
/// <summary> /// Initializes a new instance of the <see cref="VtkImageDataHandle"/> class with the <see cref="vtkImageData"/> to wrap and /// a <see cref="GCHandleType.Pinned"/> <see cref="GCHandle"/> to the managed data array to be used by VTK. /// </summary> /// <remarks> /// When this <see cref="VtkImageDataHandle"/> is disposed, both the <paramref name="vtkImageData"/> and /// the <paramref name="pinningHandle"/> will be released. /// </remarks> /// <param name="vtkImageData">The <see cref="vtk.vtkImageData"/> object holding the handle to a managed data array.</param> /// <param name="pinningHandle">A <see cref="GCHandle"/> pinning the managed data array.</param> public VtkImageDataHandle(vtkImageData vtkImageData, GCHandle pinningHandle) { Platform.CheckForNullReference(vtkImageData, "vtkImageData"); _vtkImageData = vtkImageData; _pinningHandle = pinningHandle; }
public static vtkImageData ReadMetaImage(this string mhdFileName) { GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); Stopwatch sw = Stopwatch.StartNew(); File.ReadAllBytes(mhdFileName); if (File.Exists(mhdFileName.ReplaceFileName("i.raw"))) { File.ReadAllBytes(mhdFileName.ReplaceFileName("i.raw")); } if (File.Exists(mhdFileName.ReplaceFileName("i.zraw"))) { File.ReadAllBytes(mhdFileName.ReplaceFileName("i.zraw")); } vtkMetaImageReader metaImageReader = vtkMetaImageReader.New(); metaImageReader.SetFileName(mhdFileName); metaImageReader.Update(); vtkImageData readMetaImage = metaImageReader.GetOutput(); metaImageReader.Dispose(); metaImageReader = null; sw.Stop(); //Console.WriteLine("Read {0} took {1} ms.", mhdFileName, sw.ElapsedMilliseconds); return(readMetaImage); }
/// <summary> /// Function for removing sample edges. /// </summary> /// <param name="stack"></param> /// <param name="side"></param> /// <param name="get_center"></param> /// <returns></returns> public static vtkImageData center_crop(vtkImageData stack, int side = 400, bool get_center = true) { //Get input dimensions int[] dims = stack.GetExtent(); //Find the center of the sample int x1; int x2; int y1; int y2; int[] center = find_center(stack, 70, new int[] { 0, (dims[5] - dims[4] + 1) / 3 });//GetCenter(bytedata,80); //Compute new volume sides y2 = Math.Min(center[0] + (side / 2), dims[1]); y1 = Math.Max(y2 - side + 1, dims[0]); x2 = Math.Min(center[1] + (side / 2), dims[3]); x1 = Math.Max(x2 - side + 1, dims[2]); //Create VOI extractor vtkExtractVOI cropper = vtkExtractVOI.New(); cropper.SetVOI(y1, y2, x1, x2, dims[4], dims[5]); cropper.SetInput(stack); cropper.Update(); return(cropper.GetOutput()); }
/// <summary> /// Converts 3D byte array to vtkImageData. /// </summary> /// <param name="data">Input array.</param> /// <param name="dims">Input array dimensions. Give the begin and end extent for each dimension.</param> /// <returns>Converted array.</returns> public static vtkImageData byteToVTK1D(byte[] data, int[] dims) { int h = dims[1] - dims[0] + 1; int w = dims[3] - dims[2] + 1; int d = dims[5] - dims[4] + 1; //Create VTK data for putput vtkImageData vtkdata = vtkImageData.New(); //Character array for conversion vtkUnsignedCharArray charArray = vtkUnsignedCharArray.New(); //Pin byte array GCHandle pinnedArray = GCHandle.Alloc(data, GCHandleType.Pinned); //Set character array input charArray.SetArray(pinnedArray.AddrOfPinnedObject(), h * w * d, 1); //Set vtkdata properties and connect array //Data from char array vtkdata.GetPointData().SetScalars(charArray); //Number of scalars/pixel vtkdata.SetNumberOfScalarComponents(1); //Set data extent vtkdata.SetExtent(dims[0], dims[1], dims[2], dims[3], dims[4], dims[5]); //Scalar type vtkdata.SetScalarTypeToUnsignedChar(); vtkdata.Update(); return(vtkdata); }
public static void GetRectData(vtkPolyData data, Rectangle rect) { var points = vtkPoints.New(); var colorArray = vtkUnsignedCharArray.New(); colorArray.SetNumberOfComponents(3); RectImageData = vtkImageData.New(); RectImageData.SetExtent(0, rect.Size.Width - 1, 0, rect.Size.Height - 1, 0, 0); RectImageData.SetNumberOfScalarComponents(1); RectImageData.SetScalarTypeToUnsignedChar(); for (var i = rect.Top; i < rect.Bottom; i++) { for (var j = rect.Left; j < rect.Right; j++) { double[] p = data.GetPoint(i * ImageWidth + j); points.InsertNextPoint(j - rect.Left, i - rect.Top, p[2]); double[] c = data.GetPointData().GetScalars().GetTuple3(i * ImageWidth + j); colorArray.InsertNextTuple3(c[0], c[1], c[2]); RectImageData.SetScalarComponentFromDouble(j - rect.Left, i - rect.Top, 0, 0, c[0]); } } RectPolyData = vtkPolyData.New(); RectPolyData.SetPoints(points); RectPolyData.GetPointData().SetScalars(colorArray); RectPolyData.Update(); }
// This method is used by the VolumeSlice to generate pixel data on demand internal byte[] CreateSliceNormalizedPixelData(Vector3D throughPoint) { Matrix resliceAxes = new Matrix(_slicerParams.SlicingPlaneRotation); resliceAxes[3, 0] = throughPoint.X; resliceAxes[3, 1] = throughPoint.Y; resliceAxes[3, 2] = throughPoint.Z; #if SLAB using (vtkImageData imageData = GenerateVtkSlab(resliceAxes, 10)) // baked 10 voxels for testing { byte[] pixelData = MipPixelDataFromVtkSlab(imageData); imageData.ReleaseData(); return(pixelData); } #else using (vtkImageData imageData = GenerateVtkSlice(resliceAxes)) { byte[] pixelData = CreatePixelDataFromVtkSlice(imageData); imageData.ReleaseData(); return(pixelData); } #endif }
public WatermarkPackage(vtkRenderWindow renwin, vtkRenderer mainRenderer, vtkImageData maskImage) { int oldNumberOfRenderer = renwin.GetNumberOfLayers(); Console.WriteLine(string.Format("oldNumberOfRenderer = {0}", oldNumberOfRenderer)); int newNumberOfRenderer = oldNumberOfRenderer + 1; mainRenderer.SetLayer(0); vtkRenderer _topRenderer = vtkRenderer.New(); _topRenderer.SetViewport(0, 0, 1, 1); _topRenderer.SetLayer(newNumberOfRenderer - 1); _topRenderer.InteractiveOff(); _topRenderer.GetActiveCamera().ParallelProjectionOn(); mainRenderer.SetLayer(1); _topRenderer.SetLayer(0); renwin.SetNumberOfLayers(newNumberOfRenderer); renwin.AddRenderer(_topRenderer); // Display the image _actor = vtkImageActor.New(); _actor.SetInput(maskImage); _actor.SetOpacity(0.8); _topRenderer.AddActor(_actor); _topRenderer.ResetCameraClippingRange(); _topRenderer.ResetCamera(); _topRenderer.GetActiveCamera().Zoom(1.6); }
public static vtkImageData inference_to_vtk(IList <IList <float> > input, int[] output_size, int[] extent, int axis) { int[] orientation = new int[3]; if (axis == 0) { orientation = new int[] { 2, 1, 0 }; extent = new int[] { extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] }; output_size = new int[] { output_size[0], output_size[1], output_size[2] }; } if (axis == 1) { orientation = new int[] { 1, 2, 0 }; extent = new int[] { extent[2], extent[3], extent[0], extent[1], extent[4], extent[5] }; output_size = new int[] { output_size[1], output_size[0], output_size[2] }; } if (axis == 2) { orientation = new int[] { 0, 1, 2 }; extent = new int[] { extent[4], extent[5], extent[1], extent[2], extent[3], extent[4] }; output_size = new int[] { output_size[2], output_size[0], output_size[1] }; } //Data to byte array byte[,,] bytedata = DataTypes.batchToByte(input, output_size, extent); vtkImageData output = DataTypes.byteToVTK(bytedata, orientation); return(output); }
/// <summary> /// Rotates volume along given axis. /// </summary> /// <param name="volume"></param> /// <param name="angles"></param> public static void RotateData(ref vtkImageData volume, double[] angles) { // Rotation along image center double[] center = volume.GetExtent().Divide(2); // Dimensions of rotated image int[] outExtent = volume.GetExtent().Multiply(1.1).Round().ToInt32(); // Rotation parameters var rotate = new vtkTransform(); rotate.Translate(center[1], center[3], center[5]); rotate.RotateX(angles[0]); rotate.RotateY(angles[1]); rotate.RotateZ(angles[2]); // z angle should be 0 rotate.Translate(-center[1], -center[3], -center[5]); // Perform rotation var slice = new vtkImageReslice(); slice.SetInput(volume); slice.SetResliceTransform(rotate); slice.SetInterpolationModeToCubic(); slice.SetOutputSpacing(volume.GetSpacing()[0], volume.GetSpacing()[1], volume.GetSpacing()[2]); slice.SetOutputOrigin(volume.GetOrigin()[0], volume.GetOrigin()[1], volume.GetOrigin()[2]); slice.SetOutputExtent(outExtent[0], outExtent[1], outExtent[2], outExtent[3], outExtent[4], outExtent[5]); }
void CreateData(ref vtkImageData data) { data.SetExtent(-25, 25, -25, 25, 0, 0); #if VTK_MAJOR_VERSION_5 data.SetNumberOfScalarComponents(1); data.SetScalarTypeToDouble(); #else data.AllocateScalars(VTK_DOUBLE, 1); #endif int[] extent = data.GetExtent(); for (int y = extent[2]; y <= extent[3]; y++) { for (int x = extent[0]; x <= extent[1]; x++) { IntPtr ptr = data.GetScalarPointer(x, y, 0); double[] pixel = new double[] { Math.Sqrt(Math.Pow(x, 2.0) + Math.Pow(y, 2.0)) }; Marshal.Copy(pixel, 0, ptr, 1); } } vtkXMLImageDataWriter writer = vtkXMLImageDataWriter.New(); writer.SetFileName(@"c:\vtk\vtkdata-5.8.0\Data\testIsoContours.vti"); #if VTK_MAJOR_VERSION_5 writer.SetInputConnection(data.GetProducerPort()); #else writer.SetInputData(data); #endif writer.Write(); }
private static byte[] MipPixelDataFromVtkSlab(vtkImageData slabImageData) { #if true // Do our own MIP, albeit slowly int[] sliceDimensions = slabImageData.GetDimensions(); int sliceDataSize = sliceDimensions[0] * sliceDimensions[1]; IntPtr slabDataPtr = slabImageData.GetScalarPointer(); byte[] pixelData = MemoryManager.Allocate <byte>(sliceDataSize * sizeof(short)); // Init with first slice Marshal.Copy(slabDataPtr, pixelData, 0, sliceDataSize * sizeof(short)); // Walk through other slices, finding maximum unsafe { short *psSlab = (short *)slabDataPtr; fixed(byte *pbFrame = pixelData) { short *psFrame = (short *)pbFrame; for (int sliceIndex = 1; sliceIndex < sliceDimensions[2]; sliceIndex++) { for (int i = 0; i < sliceDataSize - 1; ++i) { int slabIndex = sliceIndex * sliceDataSize + i; if (psSlab[slabIndex] > psFrame[i]) { psFrame[i] = psSlab[slabIndex]; } } } } } return(pixelData); #else // Ideally we'd use VTK to do the MIP (MinIP, Average...) vtkVolumeRayCastMIPFunction mip = new vtkVolumeRayCastMIPFunction(); vtkVolumeRayCastMapper mapper = new vtkVolumeRayCastMapper(); mapper.SetVolumeRayCastFunction(mip); mapper.SetInput(slabImageData); //TODO: Need to figure out how to use mapper to output vtkImageData vtkImageAlgorithm algo = new vtkImageAlgorithm(); algo.SetInput(mapper.GetOutputDataObject(0)); using (vtkExecutive exec = mapper.GetExecutive()) { VtkHelper.RegisterVtkErrorEvents(exec); exec.Update(); // Note: These report no output port, must have to do something else to get mapper to give us data //return exec.GetOutputData(0); return(mapper.GetOutputDataObject(0)); } #endif }
public static void SaveImageData(string imgname, vtkImageData imageData) { var bmpWriter = vtkBMPWriter.New(); bmpWriter.SetInput(imageData); bmpWriter.SetFileName(imgname); bmpWriter.Update(); }
// Static void method with same signature as "Main" is always // file base name: // /// <summary> /// VTK test Main method /// </summary> public static void vtkImageDataExtraTests(string[] args) { string vtkDataDir = ""; for (int i = 0; i < args.Length; i++) { if (args[i] == "-D") { vtkDataDir = args[i + 1]; } } //Read in bitmap and image data string bmpFile = vtkDataDir + "/Data/masonry.bmp"; vtkImageReader2 rdr = vtkImageReader2Factory.CreateImageReader2(bmpFile); rdr.SetFileName(bmpFile); rdr.Update(); vtkImageData idata = rdr.GetOutput(); System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(bmpFile); //get bytes before and after double conversion byte[] bmpArr1 = getArrayFromBitmap(bmp); vtkImageData bmp1 = vtkImageData.FromImage(bmp, 3); Bitmap bmp2 = bmp1.ToBitmap(); return; byte[] bmpArr2 = getArrayFromBitmap(bmp2); //get bytes before and after double conversion byte[] idataArr1 = getArrayFromImageData(idata); Bitmap idata1 = idata.ToBitmap(); vtkImageData idata2 = vtkImageData.FromImage(idata1, 3); byte[] idataArr2 = getArrayFromImageData(idata2); for (int i = 0; i < bmpArr1.Length; i++) { if (bmpArr1[i] != bmpArr2[i]) { throw new Exception("ERROR: Images Not Identical!"); } } for (int i = 0; i < idataArr2.Length; i++) { if (idataArr1[i] != idataArr2[i]) { throw new Exception("ERROR: Images Not Identical!"); } } rdr.Dispose(); Console.Out.WriteLine("Passed"); }
public static void WriteImageData(string imageDataPath, vtkImageData imagedata) { vtkMetaImageWriter write = new vtkMetaImageWriter(); write.SetFileName(imageDataPath); write.SetInput(imagedata); write.Write(); write.Dispose(); }
public static void SetColorByImage(vtkPolyData data, vtkImageData image, Rectangle rect) { for (int i = 0; i < rect.Width * rect.Height; i++) { float c = image.GetScalarComponentAsFloat(i % rect.Width, i / rect.Width, 0, 0); data.GetPointData().GetScalars().SetTuple3(i, c, c, c); } data.Modified(); }
/// <summary> /// Calculates average columns from 3D volume. Obsolete. /// </summary> /// <param name="averages"></param> /// <param name="steps"></param> /// <param name="input"></param> /// <param name="n_tiles"></param> public static void average_tiles(out double[,,] averages, out int[] steps, vtkImageData input, int n_tiles = 16) { //Get dimensions int[] dims = input.GetExtent(); int h = dims[1] - dims[0] + 1; int w = dims[3] - dims[2] + 1; int d = dims[5] - dims[4] + 1; //Input to byte array byte[] bytedata = DataTypes.vtkToByte(input); //Generate tile coordinates int N = (int)Math.Sqrt(n_tiles); int wh = h / N; int ww = w / N; steps = new int[] { wh, ww }; List <int[]> tiles = new List <int[]>(); for (int kh = 0; kh < N; kh++) { for (int kw = 0; kw < N; kw++) { int[] tmp = new int[] { kh *wh, (kh + 1) * wh, kw *ww, (kw + 1) * ww }; tiles.Add(tmp); } } //Iterate over tiles, and average the grayscale values //Empty array for averages double[,,] _averages = new double[N, N, d]; //Number of elements N = wh * ww; foreach (int[] tile in tiles) { for (int z = 0; z < d; z++) { Parallel.For(tile[0], tile[1], (int y) => { Parallel.For(tile[2], tile[3], (int x) => { int pos = z * (h * w) + x * (h) + y; byte val = bytedata[pos]; _averages[y / wh, x / ww, z] += (double)val; }); }); _averages[(tile[1] - 1) / wh, (tile[3] - 1) / ww, z] /= (double)N; } } averages = _averages; }
/// <summary> /// Gets a 2D slice from the 3D data. /// </summary> /// <param name="volume">Full 3D data.</param> /// <param name="sliceN">Number of slice to be selected.</param> /// <param name="axis">Axis on which selection will be made.</param> /// <returns></returns> public static vtkImageData volumeSlicer(vtkImageData volume, int[] sliceN, int axis) { //Initialize VOI extractor and permuter. //Permuter will correct the orientation of the output image vtkExtractVOI slicer = vtkExtractVOI.New(); vtkImagePermute permuter = vtkImagePermute.New(); //Connect data to slicer slicer.SetInput(volume); slicer.Update(); //Get data dimensions int[] dims = slicer.GetOutput().GetExtent(); //Get slice //Coronal plane if (axis == 0) { //Set VOI slicer.SetVOI(sliceN[0] - 1, sliceN[0], dims[2], dims[3], dims[4], dims[5]); slicer.Update(); //Permute image (not necessary here) permuter.SetInputConnection(slicer.GetOutputPort()); permuter.SetFilteredAxes(1, 2, 0); permuter.Update(); } //Transverse plane YZ if (axis == 1) { //Set VOI slicer.SetVOI(dims[0], dims[1], sliceN[1] - 1, sliceN[1], dims[4], dims[5]); slicer.Update(); //Permute image permuter.SetInputConnection(slicer.GetOutputPort()); permuter.SetFilteredAxes(0, 2, 1); permuter.Update(); } //Transverse plane, XZ if (axis == 2) { //Set VOI slicer.SetVOI(dims[0], dims[1], dims[2], dims[3], sliceN[2] - 1, sliceN[2]); slicer.Update(); //Permute image permuter.SetInputConnection(slicer.GetOutputPort()); permuter.SetFilteredAxes(0, 1, 2); permuter.Update(); } //slicer.Update(); //Return copy of the slice return(permuter.GetOutput()); }
public static vtkImageData vtkFPSuppression(vtkImageData mask, vtkImageData samplemask, int kernel_size = 25) { //Subtract BCI mask from cartilage mask vtkImageMathematics math = vtkImageMathematics.New(); math.SetInput1(samplemask); math.SetInput2(mask); math.SetOperationToSubtract(); math.Update(); //Closing vtkImageDilateErode3D dilate = vtkImageDilateErode3D.New(); dilate.SetErodeValue(0.0); dilate.SetDilateValue(1.0); dilate.SetKernelSize(kernel_size, kernel_size, kernel_size); dilate.SetInputConnection(math.GetOutputPort()); dilate.Update(); vtkImageDilateErode3D erode = vtkImageDilateErode3D.New(); erode.SetErodeValue(1.0); erode.SetDilateValue(0.0); erode.SetKernelSize(kernel_size, kernel_size, kernel_size); erode.SetInputConnection(dilate.GetOutputPort()); erode.Update(); //Subtract closed mask from BCI mask math.Dispose(); math = vtkImageMathematics.New(); math.SetInput1(mask); math.SetInput2(erode.GetOutput()); math.SetOperationToSubtract(); math.Update(); //Dilate the BCI mask dilate.Dispose(); dilate = vtkImageDilateErode3D.New(); dilate.SetErodeValue(0.0); dilate.SetDilateValue(1.0); dilate.SetKernelSize(kernel_size, kernel_size, kernel_size); dilate.SetInputConnection(math.GetOutputPort()); dilate.Update(); //Multiply the original BCI mask with the dilated math.Dispose(); math = vtkImageMathematics.New(); math.SetInput1(mask); math.SetInput2(dilate.GetOutput()); math.SetOperationToMultiply(); math.Update(); return(math.GetOutput()); }
private static byte[] CreatePixelDataFromVtkSlice(vtkImageData sliceImageData) { int[] sliceDimensions = sliceImageData.GetDimensions(); int sliceDataSize = sliceDimensions[0] * sliceDimensions[1]; IntPtr sliceDataPtr = sliceImageData.GetScalarPointer(); byte[] pixelData = MemoryManager.Allocate <byte>(sliceDataSize * sizeof(short)); Marshal.Copy(sliceDataPtr, pixelData, 0, sliceDataSize * sizeof(short)); return(pixelData); }
private vtkImageData CreateVolumeImageData() { vtkImageData imageData = new vtkImageData(); imageData.SetDimensions(this.Width, this.Height, this.Depth); imageData.SetSpacing(GetFirstFrame().PixelSpacing.Column, GetFirstFrame().PixelSpacing.Row, GetSliceSpacing()); imageData.AllocateScalars(); imageData.SetScalarTypeToUnsignedShort(); imageData.GetPointData().SetScalars(BuildVolumeImageData()); return(imageData); }
/// <summary> /// Creates byte array from vtkImageData /// </summary> /// <param name="idata"></param> /// <returns></returns> public static byte[] getArrayFromImageData(vtkImageData idata) { int width = (int)(idata.GetBounds()[1] - idata.GetBounds()[0]) + 1; int height = (int)(idata.GetBounds()[3] - idata.GetBounds()[2]) + 1; byte[] arr = new byte[width * height * idata.GetNumberOfScalarComponents()]; System.Runtime.InteropServices.Marshal.Copy( ((IntPtr)idata.GetScalarPointer()), arr, 0, width * height * idata.GetNumberOfScalarComponents()); return arr; }
private static void ResliceVolume(vtkImageData volume) { using (var reslicer = new vtkImageReslice()) { RegisterVtkErrorEvents(reslicer); reslicer.SetInput(volume); reslicer.SetInformationInput(volume); // Must instruct reslicer to output 2D images reslicer.SetOutputDimensionality(2); // Use the volume's padding value for all pixels that are outside the volume reslicer.SetBackgroundLevel(0); // This ensures VTK obeys the real spacing, results in all VTK slices being isotropic. // Effective spacing is the minimum of these three. reslicer.SetOutputSpacing(1.0, 1.0, 1.0); using (vtkMatrix4x4 resliceAxesMatrix = ConvertToVtkMatrix(new double[, ] { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } })) { reslicer.SetResliceAxes(resliceAxesMatrix); // Clamp the output based on the slice extent const int sliceExtentX = 50; const int sliceExtentY = 50; reslicer.SetOutputExtent(0, sliceExtentX - 1, 0, sliceExtentY - 1, 0, 0); // Set the output origin to reflect the slice through point. The slice extent is // centered on the slice through point. // VTK output origin is derived from the center image being 0,0 const float originX = -sliceExtentX * 1f / 2; const float originY = -sliceExtentY * 1f / 2; reslicer.SetOutputOrigin(originX, originY, 0); reslicer.SetInterpolationModeToLinear(); using (vtkExecutive exec = reslicer.GetExecutive()) { RegisterVtkErrorEvents(exec); exec.Update(); } using (var output = reslicer.GetOutput()) { // just to give it something to do with the output GC.KeepAlive(output); } } } }
/// <summary> /// Creates byte array from vtkImageData /// </summary> /// <param name="idata"></param> /// <returns></returns> static public byte[] getArrayFromImageData(vtkImageData idata) { int width = (int)(idata.GetBounds()[1] - idata.GetBounds()[0]) + 1; int height = (int)(idata.GetBounds()[3] - idata.GetBounds()[2]) + 1; byte[] arr = new byte[width * height * idata.GetNumberOfScalarComponents()]; System.Runtime.InteropServices.Marshal.Copy( ((IntPtr)idata.GetScalarPointer()), arr, 0, width * height * idata.GetNumberOfScalarComponents()); return(arr); }
/// <summary> /// Removes surface artefacts from the sample. /// </summary> /// <param name="volume">Sample volume data.</param> /// <param name="points">Points for removal line.</param> /// <param name="axis">Axis of removal.</param> /// <returns>Sample data without artefacts</returns> public static vtkImageData remove_artefacts(vtkImageData volume, double[] points, int axis) { //Get input volume dimensions int[] dims = volume.GetExtent(); int h = dims[1] - dims[0] + 1; int w = dims[3] - dims[2] + 1; int d = dims[5] - dims[4] + 1; Console.WriteLine("Got dims: {0},{1},{2}", h, w, d); //Convert volume to byte array byte[] bytedata = DataTypes.vtkToByte(volume); Console.WriteLine("Got bytedata"); //Compute slope (k) and zero crossing (b) from given point for a line y=kx+b //Compute the slope of the line from points double slope = (points[3] - points[1]) / (points[2] - points[0]); //Compute zero crossing double b = points[3] - slope * points[2] - dims[4]; Console.WriteLine("Got line equation"); //Iterate over the data Parallel.For(0, h, (int y) => { Parallel.For(0, w, (int x) => { //Compute extent for zeroing int zstart = 0; int zstop = d; if (axis == 0) { zstart = (int)((double)(x + dims[2]) * slope + b); zstart = Math.Max(zstart, 0); } if (axis == 1) { zstart = (int)((double)(y + dims[0]) * slope + b); zstart = Math.Max(zstart, 0); } //Iterate over z-axis for (int z = zstart; z < zstop; z++) { int pos = z * (h * w) + x * h + y; bytedata[pos] = 0; } }); }); Console.WriteLine("Zeroed"); //Convert byte data back to vtkdata vtkImageData output = DataTypes.byteToVTK1D(bytedata, dims); return(output); }
public fy3DModelPage(ExGrid Grid, double[] CameraFocalPoint, double[] CameraPoint, double[] CameraViewUp) { InitializeComponent(); m_PageMode = fy3DModelPageMode.Normal_Mode; m_CameraFocalPoint = CameraFocalPoint; m_CameraPoint = CameraPoint; m_CameraViewUp = CameraViewUp; m_ImageData = ConvertfyGrid2vtkImageData(Grid); //初始化渲染的颜色和透明度 InitializeColor_Normal(Grid); }
public static vtkImageData ReadMetaImageData(string filePath) { vtkMetaImageReader reader = new vtkMetaImageReader(); reader.SetFileName(filePath); reader.Update(); vtkImageData imagedata = reader.GetOutput(); reader.Dispose(); return(imagedata); }
private void IsoContours() { vtkImageData data = vtkImageData.New(); CreateData(ref data); // Create an isosurface _ContourFilter = vtkContourFilter.New(); #if VTK_MAJOR_VERSION_5 _ContourFilter.SetInput(data); #else contourFilter.SetInputData(data); #endif _ContourFilter.GenerateValues(1, 10, 10); // (numContours, rangeStart, rangeEnd) // Map the contours to graphical primitives vtkPolyDataMapper contourMapper = vtkPolyDataMapper.New(); #if VTK_MAJOR_VERSION_5 contourMapper.SetInputConnection(_ContourFilter.GetOutputPort()); #else contourMapper.SetInputData(contourFilter); #endif // Create an actor for the contours vtkActor contourActor = vtkActor.New(); contourActor.SetMapper(contourMapper); // Create the outline vtkOutlineFilter outlineFilter = vtkOutlineFilter.New(); vtkPolyDataMapper outlineMapper = vtkPolyDataMapper.New(); #if VTK_MAJOR_VERSION_5 outlineFilter.SetInput(data); outlineMapper.SetInputConnection(outlineFilter.GetOutputPort()); #else outlineFilter.SetInputData(data); outlineMapper.SetInputData(outlineFilter); #endif vtkActor outlineActor = vtkActor.New(); outlineActor.SetMapper(outlineMapper); // get a reference to the renderwindow of our renderWindowControl1 _RenderWindow = renderWindowControl1.RenderWindow; // renderer vtkRenderer renderer = _RenderWindow.GetRenderers().GetFirstRenderer(); // set background color renderer.SetBackground(.2, .3, .4); // add our actor to the renderer renderer.AddActor(contourActor); renderer.AddActor(outlineActor); }
public static void ReadDataFromFile(string filename) { try { SimplePointFile.GetImageInfo(filename); ImageWidth = SimplePointFile.ImageWidth; ImageHeight = SimplePointFile.ImageHeight; //Console.WriteLine("ImageWidth:" + ImageWidth); //Console.WriteLine("ImageHeight:" + ImageHeight); var points = vtkPoints.New(); var colorArray = vtkUnsignedCharArray.New(); colorArray.SetNumberOfComponents(3); ImageData = vtkImageData.New(); ImageData.SetExtent(0, ImageWidth - 1, 0, ImageHeight - 1, 0, 0); ImageData.SetNumberOfScalarComponents(1); ImageData.SetScalarTypeToUnsignedChar(); SimplePointFile.OpenReadFile(filename); double[] data; while ((data = SimplePointFile.ReadLine()) != null) { points.InsertNextPoint(data[0], data[1], data[2]); colorArray.InsertNextTuple3(data[3], data[4], data[5]); ImageData.SetScalarComponentFromDouble((int)data[0], (int)data[1], 0, 0, data[3]); } PolyData = vtkPolyData.New(); PolyData.SetPoints(points); PolyData.GetPointData().SetScalars(colorArray); PolyData.Update(); //Console.WriteLine("PolyData & ImageData Load."); } catch (Exception e) { MessageBox.Show(e.Message); } finally { SimplePointFile.CloseReadFile(); } }
private void Dispose(bool disposing) { if (_disposed) return; if (disposing && _vtkVolume != null) { _vtkVolume.GetPointData().Dispose(); _vtkVolume.Dispose(); _vtkVolume = null; } _volumeArrayPinned.Free(); _disposed = true; }
void CreateVectorField(ref vtkImageData image) { // Specify the size of the image data image.SetDimensions(3, 3, 3); image.SetNumberOfScalarComponents(3); image.SetScalarTypeToFloat(); image.AllocateScalars(); image.SetSpacing(10.0, 10.0, 10.0); int[] dims = image.GetDimensions(); float[] pixel = new float[] {0.0f, 0.0f, 0.0f}; IntPtr pPixel; // Zero the vectors for(int z = 0; z < dims[2]; z++) { for(int y = 0; y < dims[1]; y++) { for(int x = 0; x < dims[0]; x++) { pPixel = image.GetScalarPointer(x, y, 0); Marshal.Copy(pixel, 0, pPixel, 3); } } } // Set two of the pixels to non zero values pixel[0] = 8.0f; pixel[1] = 8.0f; pixel[2] = -8.0f; pPixel = image.GetScalarPointer(0, 2, 0); Marshal.Copy(pixel, 0, pPixel, 3); pixel[0] = 8.0f; pixel[1] = -8.0f; pixel[2] = 8.0f; pPixel = image.GetScalarPointer(2, 0, 2); Marshal.Copy(pixel, 0, pPixel, 3); }
/// <summary> /// Call to obtain a VTK volume structure that is safe for VTK to operate on. When done /// operating on the volume, call <see cref="ReleasePinnedVtkVolume"/>. /// </summary> /// <returns></returns> internal vtkImageData ObtainPinnedVtkVolume() { //TODO: Wrap with disposable object and have released on Dispose // Create the VTK volume wrapper if it doesn't exist if (_cachedVtkVolume == null) _cachedVtkVolume = CreateVtkVolume(); // Pin the managed volume array. If not null, then already pinned so we do not re-pin. if (_volumeArrayPinnedHandle == null) { if (!this.Signed) _volumeArrayPinnedHandle = GCHandle.Alloc(_volumeDataUInt16, GCHandleType.Pinned); else _volumeArrayPinnedHandle = GCHandle.Alloc(_volumeDataInt16, GCHandleType.Pinned); } return _cachedVtkVolume; }
private static byte[] CreatePixelDataFromVtkSlice(vtkImageData sliceImageData) { int[] sliceDimensions = sliceImageData.GetDimensions(); int sliceDataSize = sliceDimensions[0]*sliceDimensions[1]; IntPtr sliceDataPtr = sliceImageData.GetScalarPointer(); if (sliceDataPtr.Equals(IntPtr.Zero)) return null; byte[] pixelData = MemoryManager.Allocate<byte>(sliceDataSize*sizeof (short)); Marshal.Copy(sliceDataPtr, pixelData, 0, sliceDataSize*sizeof (short)); return pixelData; }
private static byte[] MipPixelDataFromVtkSlab(vtkImageData slabImageData) { VtkHelper.StaticInitializationHack(); #if true // Do our own MIP, albeit slowly int[] sliceDimensions = slabImageData.GetDimensions(); int sliceDataSize = sliceDimensions[0] * sliceDimensions[1]; IntPtr slabDataPtr = slabImageData.GetScalarPointer(); byte[] pixelData = MemoryManager.Allocate<byte>(sliceDataSize * sizeof(short)); // Init with first slice Marshal.Copy(slabDataPtr, pixelData, 0, sliceDataSize * sizeof(short)); // Walk through other slices, finding maximum unsafe { short* psSlab = (short*) slabDataPtr; fixed (byte* pbFrame = pixelData) { short* psFrame = (short*)pbFrame; for (int sliceIndex = 1; sliceIndex < sliceDimensions[2]; sliceIndex++) { for (int i = 0; i < sliceDataSize-1; ++i) { int slabIndex = sliceIndex * sliceDataSize + i; if (psSlab[slabIndex] > psFrame[i]) psFrame[i] = psSlab[slabIndex]; } } } } return pixelData; #else // Ideally we'd use VTK to do the MIP (MinIP, Average...) vtkVolumeRayCastMIPFunction mip = new vtkVolumeRayCastMIPFunction(); vtkVolumeRayCastMapper mapper = new vtkVolumeRayCastMapper(); mapper.SetVolumeRayCastFunction(mip); mapper.SetInput(slabImageData); //TODO: Need to figure out how to use mapper to output vtkImageData vtkImageAlgorithm algo = new vtkImageAlgorithm(); algo.SetInput(mapper.GetOutputDataObject(0)); using (vtkExecutive exec = mapper.GetExecutive()) { VtkHelper.RegisterVtkErrorEvents(exec); exec.Update(); // Note: These report no output port, must have to do something else to get mapper to give us data //return exec.GetOutputData(0); return mapper.GetOutputDataObject(0); } #endif }
private static byte[] ReadVtkImageData(vtkImageData imageData) { // get the pointer to the image data var pData = imageData.GetScalarPointer(); if (pData.Equals(IntPtr.Zero)) return null; // get number of pixels in data var dataDimensions = imageData.GetDimensions(); var dataCount = dataDimensions[0]*dataDimensions[1]*dataDimensions[2]; // compute byte length of data var dataLength = dataCount*imageData.GetScalarSize(); // copy data to managed buffer var pixelData = MemoryManager.Allocate<byte>(dataLength); Marshal.Copy(pData, pixelData, 0, dataLength); return pixelData; }
private static byte[] SlabVtkImageData(vtkImageData slabData, Action<IntPtr, byte[], int, int, int, bool> slabAggregator, int bitsPerVoxel, bool signed) { // get the pointer to the image data var pData = slabData.GetScalarPointer(); if (pData.Equals(IntPtr.Zero)) return null; // get number of subsamples and pixels per subsample var dataDimensions = slabData.GetDimensions(); var subsamplePixels = dataDimensions[0]*dataDimensions[1]; var subsamples = dataDimensions[2]; // compute byte length of slabbed output data var dataLength = subsamplePixels*slabData.GetScalarSize(); // slab data to managed buffer var pixelData = MemoryManager.Allocate<byte>(dataLength); slabAggregator.Invoke(pData, pixelData, subsamples, subsamplePixels, bitsPerVoxel/8, signed); return pixelData; }
private static void ResliceVolume(vtkImageData volume) { using (var reslicer = new vtkImageReslice()) { RegisterVtkErrorEvents(reslicer); reslicer.SetInput(volume); reslicer.SetInformationInput(volume); // Must instruct reslicer to output 2D images reslicer.SetOutputDimensionality(2); // Use the volume's padding value for all pixels that are outside the volume reslicer.SetBackgroundLevel(0); // This ensures VTK obeys the real spacing, results in all VTK slices being isotropic. // Effective spacing is the minimum of these three. reslicer.SetOutputSpacing(1.0, 1.0, 1.0); using (vtkMatrix4x4 resliceAxesMatrix = ConvertToVtkMatrix(new double[,] {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}})) { reslicer.SetResliceAxes(resliceAxesMatrix); // Clamp the output based on the slice extent const int sliceExtentX = 50; const int sliceExtentY = 50; reslicer.SetOutputExtent(0, sliceExtentX - 1, 0, sliceExtentY - 1, 0, 0); // Set the output origin to reflect the slice through point. The slice extent is // centered on the slice through point. // VTK output origin is derived from the center image being 0,0 const float originX = -sliceExtentX*1f/2; const float originY = -sliceExtentY*1f/2; reslicer.SetOutputOrigin(originX, originY, 0); reslicer.SetInterpolationModeToLinear(); using (vtkExecutive exec = reslicer.GetExecutive()) { RegisterVtkErrorEvents(exec); exec.Update(); } using (var output = reslicer.GetOutput()) { // just to give it something to do with the output GC.KeepAlive(output); } } } }
private static vtkImageData CreateVtkVolume(short[] data, int width, int height, int depth) { var vtkVolume = new vtkImageData(); RegisterVtkErrorEvents(vtkVolume); vtkVolume.SetDimensions(width, height, depth); vtkVolume.SetOrigin(0, 0, 0); vtkVolume.SetSpacing(1.0, 1.0, 1.0); using (var array = ConvertToVtkShortArray(data)) { vtkVolume.SetScalarTypeToShort(); vtkVolume.GetPointData().SetScalars(array); // This call is necessary to ensure vtkImageData data's info is correct (e.g. updates WholeExtent values) vtkVolume.UpdateInformation(); } return vtkVolume; }
public VtkVolumeHandle(vtkImageData vtkVolume, GCHandle volumeArrayPinned) { _vtkVolume = vtkVolume; _volumeArrayPinned = volumeArrayPinned; }
//private void CommonInit(Sequence BinarySubImageSeq) //{ // vtkImageData ImageData1 = new vtkImageData(); // ImageData1.SetDimensions(BinarySubImageSeq.Width, BinarySubImageSeq.Height, BinarySubImageSeq.Depth); // ImageData1.SetNumberOfScalarComponents(1); // ImageData1.SetSpacing(BinarySubImageSeq.XResolution, BinarySubImageSeq.YResolution, BinarySubImageSeq.ZResolution); // ImageData1.SetScalarTypeToFloat(); // vtkFloatArray array1 = new vtkFloatArray(); // for (int i = 0; i < BinarySubImageSeq.ImageSize; i++) // array1.InsertTuple1(i, BinarySubImageSeq[0].Data[0][i]); // ImageData1.GetPointData().SetScalars(array1); // vtkExtractVOI VOI = new vtkExtractVOI(); // VOI.SetInput(ImageData1); // VOI.SetSampleRate(1, 1, 1); // vtkMarchingCubes ContourObject = vtkMarchingCubes.New(); // vtk_PolyDataMapper = vtkPolyDataMapper.New(); // //ContourActor = new vtkActor(); // VOI.SetVOI(0, BinarySubImageSeq.Width - 1, 0, BinarySubImageSeq.Height - 1, 0, BinarySubImageSeq.Depth - 1); // ContourObject.SetInput(VOI.GetOutput()); // ContourObject.SetValue(0, 0.5); // vtk_PolyDataMapper.SetInput(ContourObject.GetOutput()); // vtk_PolyDataMapper.ScalarVisibilityOn(); // vtk_PolyDataMapper.SetScalarModeToUseFieldData(); //} ///// <summary> ///// Generate a 3D mesh using marching-cubes algorithm. If voxel value is lower than 1 it is consider as background, else as object ///// </summary> ///// <param name="BinarySubImageSeq">The binary image</param> ///// <param name="Colour">Mesh color</param> ///// <param name="Pos">Postion of the object in the world</param> //public void Generate(Sequence BinarySubImageSeq, Color Colour, cPoint3D Pos) //{ // vtkImageData ImageData1 = new vtkImageData(); // ImageData1.SetDimensions(BinarySubImageSeq.Width, BinarySubImageSeq.Height, BinarySubImageSeq.Depth); // ImageData1.SetNumberOfScalarComponents(1); // ImageData1.SetSpacing(BinarySubImageSeq.XResolution, BinarySubImageSeq.YResolution, BinarySubImageSeq.ZResolution); // ImageData1.SetScalarTypeToFloat(); // vtkFloatArray array1 = new vtkFloatArray(); // for (int i = 0; i < BinarySubImageSeq.ImageSize; i++) // array1.InsertTuple1(i, BinarySubImageSeq[0].Data[0][i]); // ImageData1.GetPointData().SetScalars(array1); // vtkExtractVOI VOI = new vtkExtractVOI(); // VOI.SetInput(ImageData1); // VOI.SetSampleRate(1, 1, 1); // vtkMarchingCubes ContourObject = vtkMarchingCubes.New(); // vtk_PolyDataMapper = vtkPolyDataMapper.New(); // //ContourActor = new vtkActor(); // VOI.SetVOI(0, BinarySubImageSeq.Width - 1, 0, BinarySubImageSeq.Height - 1, 0, BinarySubImageSeq.Depth - 1); // // perform the amrching cubes // ContourObject.SetInput(VOI.GetOutput()); // ContourObject.SetValue(0, 0.5); // //vtkDecimatePro deci // //deci SetInputConnection [fran GetOutputPort] // //deci SetTargetReduction 0.9 // //deci PreserveTopologyOn // if (MeshSmoother!=null) // { // vtkSmoothPolyDataFilter smoother = new vtkSmoothPolyDataFilter(); // smoother.SetInputConnection(ContourObject.GetOutputPort());// [deci GetOutputPort] // smoother.SetNumberOfIterations(50); // vtk_PolyData = smoother.GetOutput(); // } // else // { // vtk_PolyData = ContourObject.GetOutput(); // } // vtk_PolyDataMapper.SetInput(vtk_PolyData); // vtk_PolyDataMapper.ScalarVisibilityOn(); // vtk_PolyDataMapper.SetScalarModeToUseFieldData(); // this.Position = new cPoint3D(Pos.X, Pos.Y, Pos.Z); // this.Colour = Colour; // CreateVTK3DObject(1); // vtk_PolyData = ContourObject.GetOutput(); // // compute convex hull // hullFilter = vtkHull.New(); // hullFilter.SetInputConnection(ContourObject.GetOutputPort()); // hullFilter.AddRecursiveSpherePlanes(1); // hullFilter.Update(); // // this.BackfaceCulling(false); // Information = new cInformation(ContourObject, this, hullFilter); //} public void Generate(cImage BinarySubImageSeq, Color Colour, cPoint3D Pos/*, List<cBiological3DObject> Containers, int ContainerMode*/) { vtkImageData ImageData1 = new vtkImageData(); ImageData1.SetDimensions(BinarySubImageSeq.Width, BinarySubImageSeq.Height, BinarySubImageSeq.Depth); ImageData1.SetNumberOfScalarComponents(1); ImageData1.SetSpacing(BinarySubImageSeq.Resolution.X, BinarySubImageSeq.Resolution.Y, BinarySubImageSeq.Resolution.Z); ImageData1.SetScalarTypeToFloat(); vtkFloatArray array1 = new vtkFloatArray(); for (int i = 0; i < BinarySubImageSeq.ImageSize; i++) array1.InsertTuple1(i, BinarySubImageSeq.SingleChannelImage[0].Data[i]); ImageData1.GetPointData().SetScalars(array1); vtkExtractVOI VOI = new vtkExtractVOI(); VOI.SetInput(ImageData1); VOI.SetSampleRate(1, 1, 1); vtkMarchingCubes ContourObject = vtkMarchingCubes.New(); vtk_PolyDataMapper = vtkPolyDataMapper.New(); //ContourActor = new vtkActor(); VOI.SetVOI(0, BinarySubImageSeq.Width - 1, 0, BinarySubImageSeq.Height - 1, 0, BinarySubImageSeq.Depth - 1); ContourObject.SetInput(VOI.GetOutput()); ContourObject.SetValue(0, 0.5); vtkAlgorithmOutput AlgoOutPut = null; if (MeshSmoother != null) { //vtkSmoothPolyDataFilter smoother = new vtkSmoothPolyDataFilter(); vtkWindowedSincPolyDataFilter smoother = new vtkWindowedSincPolyDataFilter(); smoother.SetInputConnection(ContourObject.GetOutputPort());// [deci GetOutputPort] smoother.SetNumberOfIterations(MeshSmoother.NumberOfIterations); vtk_PolyData = smoother.GetOutput(); //smoother.GetOutputPort(); AlgoOutPut = smoother.GetOutputPort(); } else { vtk_PolyData = ContourObject.GetOutput(); AlgoOutPut = ContourObject.GetOutputPort(); } vtk_PolyDataMapper.SetInput(vtk_PolyData); vtk_PolyDataMapper.ScalarVisibilityOn(); vtk_PolyDataMapper.SetScalarModeToUseFieldData(); vtkActor TmpActor = vtkActor.New(); TmpActor.SetMapper(vtk_PolyDataMapper); TmpActor.SetPosition(Pos.X, Pos.Y, Pos.Z); //Console.WriteLine("PosX"+Pos.X+" PosY"+Pos.Y+" PosZ"+Pos.Z); #region deal with the containers if (this.Containers != null) { if (this.Containers.ContainerMode == 0) { cPoint3D Centroid = new cPoint3D((float)TmpActor.GetCenter()[0], (float)TmpActor.GetCenter()[1], (float)TmpActor.GetCenter()[2]); bool IsInside = false; for (int Idx = 0; Idx < Containers.Containers.Count; Idx++) { cBiological3DVolume CurrentContainer = (cBiological3DVolume)(Containers.Containers[Idx]); if (CurrentContainer.IsPointInside(Centroid)) { IsInside = true; ContainerIdx = Idx; break; } } if (IsInside) { this.SetPosition(new cPoint3D(Pos.X, Pos.Y, Pos.Z)); this.Colour = Colour; CreateVTK3DObject(1); // vtk_PolyData = ContourObject.GetOutput(); // compute convex hull hullFilter = vtkHull.New(); hullFilter.SetInputConnection(AlgoOutPut); hullFilter.AddRecursiveSpherePlanes(0); hullFilter.Update(); Information = new cInformation(AlgoOutPut, this, hullFilter); this.Detected = true; } else { this.Detected = false; } } else if (Containers.ContainerMode == 1) { this.Detected = true; //bool IsInside = false; for (int Idx = 0; Idx < Containers.Containers.Count; Idx++) { cBiological3DVolume CurrentContainer = (cBiological3DVolume)(Containers.Containers[Idx]); if (CurrentContainer.IsPointInside(Pos)) { //IsInside = false; this.Detected = false; return; } } this.SetPosition(new cPoint3D(Pos.X, Pos.Y, Pos.Z)); this.Colour = Colour; CreateVTK3DObject(1); // vtk_PolyData = ContourObject.GetOutput(); // compute convex hull hullFilter = vtkHull.New(); hullFilter.SetInputConnection(AlgoOutPut); hullFilter.AddRecursiveSpherePlanes(0); hullFilter.Update(); Information = new cInformation(AlgoOutPut, this, hullFilter); this.Detected = true; } } else { this.SetPosition(new cPoint3D(Pos.X, Pos.Y, Pos.Z)); this.Colour = Colour; CreateVTK3DObject(1); // vtk_PolyData = ContourObject.GetOutput(); // compute convex hull hullFilter = vtkHull.New(); hullFilter.SetInputConnection(AlgoOutPut); hullFilter.AddRecursiveSpherePlanes(1); hullFilter.Update(); // this.BackfaceCulling(false); Information = new cInformation(AlgoOutPut, this, hullFilter); } #endregion }
private void Dispose(bool disposing) { if (_disposed) return; if (disposing && _vtkImageData != null) { _vtkImageData.GetPointData().Dispose(); _vtkImageData.Dispose(); _vtkImageData = null; } _pinningHandle.Free(); _disposed = true; }
private vtkImageData CreateVolumeImageData() { vtkImageData imageData = new vtkImageData(); imageData.SetDimensions(this.Width, this.Height, this.Depth); imageData.SetSpacing(GetFirstFrame().PixelSpacing.Column, GetFirstFrame().PixelSpacing.Row, GetSliceSpacing()); imageData.AllocateScalars(); imageData.SetScalarTypeToUnsignedShort(); imageData.GetPointData().SetScalars(BuildVolumeImageData()); return imageData; }
private static vtkImageData CreateVtkVolume(Volume volume) { var vtkVolume = new vtkImageData(); vtkVolume.RegisterVtkErrorEvents(); vtkVolume.SetDimensions(volume.ArrayDimensions.Width, volume.ArrayDimensions.Height, volume.ArrayDimensions.Depth); vtkVolume.SetOrigin(0, 0, 0); vtkVolume.SetSpacing(volume.VoxelSpacing.X, volume.VoxelSpacing.Y, volume.VoxelSpacing.Z); if (volume.BitsPerVoxel == 16) { if (!volume.Signed) { using (var array = new vtkUnsignedShortArray()) { array.SetArray((ushort[]) volume.Array, (VtkIdType) volume.ArrayLength, 1); vtkVolume.SetScalarTypeToUnsignedShort(); vtkVolume.GetPointData().SetScalars(array); } } else { using (var array = new vtkShortArray()) { array.SetArray((short[]) volume.Array, (VtkIdType) volume.ArrayLength, 1); vtkVolume.SetScalarTypeToShort(); vtkVolume.GetPointData().SetScalars(array); } } } else if (volume.BitsPerVoxel == 8) { if (!volume.Signed) { using (var array = new vtkUnsignedCharArray()) { array.SetArray((byte[]) volume.Array, (VtkIdType) volume.ArrayLength, 1); vtkVolume.SetScalarTypeToUnsignedChar(); vtkVolume.GetPointData().SetScalars(array); } } else { using (var array = new vtkSignedCharArray()) { array.SetArray((sbyte[]) volume.Array, (VtkIdType) volume.ArrayLength, 1); vtkVolume.SetScalarTypeToSignedChar(); vtkVolume.GetPointData().SetScalars(array); } } } else { throw new NotSupportedException("Unsupported volume scalar type."); } // This call is necessary to ensure vtkImageData data's info is correct (e.g. updates WholeExtent values) vtkVolume.UpdateInformation(); return vtkVolume; }
private vtkImageData CreateVtkVolume() { vtkImageData vtkVolume = new vtkImageData(); VtkHelper.RegisterVtkErrorEvents(vtkVolume); vtkVolume.SetDimensions(ArrayDimensions.Width, ArrayDimensions.Height, ArrayDimensions.Depth); vtkVolume.SetOrigin(Origin.X, Origin.Y, Origin.Z); vtkVolume.SetSpacing(VoxelSpacing.X, VoxelSpacing.Y, VoxelSpacing.Z); if (!this.Signed) { vtkVolume.SetScalarTypeToUnsignedShort(); vtkVolume.GetPointData().SetScalars( VtkHelper.ConvertToVtkUnsignedShortArray(_volumeDataUInt16)); } else { vtkVolume.SetScalarTypeToShort(); vtkVolume.GetPointData().SetScalars( VtkHelper.ConvertToVtkShortArray(_volumeDataInt16)); } // This call is necessary to ensure vtkImageData data's info is correct (e.g. updates WholeExtent values) vtkVolume.UpdateInformation(); return vtkVolume; }
///<summary> A Set Method for Static Variables </summary> public static void Setdata(vtkImageData toSet) { data = toSet; }
/// <summary> /// The main entry method called by the CSharp driver /// </summary> /// <param name="argv"></param> public static void AVTestCutMaterial(String [] argv) { //Prefix Content is: "" // Lets create a data set.[] data = new vtkImageData(); data.SetExtent((int)0,(int)31,(int)0,(int)31,(int)0,(int)31); data.SetScalarTypeToFloat(); // First the data array:[] gauss = new vtkImageGaussianSource(); gauss.SetWholeExtent((int)0,(int)30,(int)0,(int)30,(int)0,(int)30); gauss.SetCenter((double)18,(double)12,(double)20); gauss.SetMaximum((double)1.0); gauss.SetStandardDeviation((double)10.0); gauss.Update(); a = gauss.GetOutput().GetPointData().GetScalars(); a.SetName((string)"Gauss"); data.GetCellData().SetScalars((vtkDataArray)a); //skipping Delete gauss // Now the material array:[] ellipse = new vtkImageEllipsoidSource(); ellipse.SetWholeExtent((int)0,(int)30,(int)0,(int)30,(int)0,(int)30); ellipse.SetCenter((double)11,(double)12,(double)13); ellipse.SetRadius((double)5,(double)9,(double)13); ellipse.SetInValue((double)1); ellipse.SetOutValue((double)0); ellipse.SetOutputScalarTypeToInt(); ellipse.Update(); m = ellipse.GetOutput().GetPointData().GetScalars(); m.SetName((string)"Material"); data.GetCellData().AddArray((vtkAbstractArray)m); //skipping Delete ellipse cut = new vtkCutMaterial(); cut.SetInput((vtkDataObject)data); cut.SetMaterialArrayName((string)"Material"); cut.SetMaterial((int)1); cut.SetArrayName((string)"Gauss"); cut.SetUpVector((double)1,(double)0,(double)0); cut.Update(); mapper2 = vtkPolyDataMapper.New(); mapper2.SetInputConnection((vtkAlgorithmOutput)cut.GetOutputPort()); mapper2.SetScalarRange((double)0,(double)1); //apper2 SetScalarModeToUseCellFieldData[] //apper2 SetColorModeToMapScalars [] //apper2 ColorByArrayComponent "vtkGhostLevels" 0[] actor2 = new vtkActor(); actor2.SetMapper((vtkMapper)mapper2); actor2.SetPosition((double)1.5,(double)0,(double)0); ren = vtkRenderer.New(); ren.AddActor((vtkProp)actor2); renWin = vtkRenderWindow.New(); renWin.AddRenderer((vtkRenderer)ren); p = cut.GetCenterPoint(); n = cut.GetNormal(); cam = ren.GetActiveCamera(); cam.SetFocalPoint(p[0],p[1],p[2]); cam.SetViewUp(cut.GetUpVector()[0], cut.GetUpVector()[1], cut.GetUpVector()[2]); cam.SetPosition( (double)(lindex(n,0))+(double)(lindex(p,0)), (double)(lindex(n,1))+(double)(lindex(p,1)), (double)(lindex(n,2))+(double)(lindex(p,2))); ren.ResetCamera(); iren = vtkRenderWindowInteractor.New(); iren.SetRenderWindow(renWin); iren.Initialize(); //deleteAllVTKObjects(); }
/// <summary> /// Update the 2D visualization when the plane moved. /// </summary> /// <param name="plane">PlaneWidget which changed the coordinates.</param> public void PlaneMoved(vtkImagePlaneWidget plane) { vtkImageReslice reslice = vtkImageReslice.New(); vtkTransform transform = vtkTransform.New(); transform.PostMultiply(); //TODO wyznaczenie centrum okna double[] center = {75, 100, 0}; transform.Translate( -center[0], -center[1], -center[2] ); transform.RotateZ(_orientation); transform.Translate( +center[0], +center[1], +center[2] ); transform.Update(); reslice.SetInput(plane.GetResliceOutput()); reslice.SetResliceTransform(transform); reslice.Update(); // vtkImageData viewerInputData; viewerInputData = reslice.GetOutput(); _lastData = viewerInputData; _viewer.SetInput(viewerInputData); // //_viewer.SetInput(reslice.GetOutput()); UpdateViewer(); }
public cVolumeRendering3D(vtkImageData imageData, cPoint3D Pos) { baseInit(null); vtk_volume = vtkVolume.New(); // vtkFloatArray floatArray = vtkFloatArray.New(); //vtkCharArray charArray = vtkCharArray.New(); // vtkUnsignedShortArray UshortArray = vtkUnsignedShortArray.New(); vtkExtractVOI voi = vtkExtractVOI.New(); // vtkPiecewiseFunction opacityTransferFunction = vtkPiecewiseFunction.New(); vtkColorTransferFunction colorTransferFunction = vtkColorTransferFunction.New(); vtkVolumeProperty volumeProperty = vtkVolumeProperty.New(); // imageData.GetPointData().SetScalars(UshortArray); voi = vtkExtractVOI.New(); voi.SetInput(imageData); voi.SetVOI(0, imageData.GetDimensions()[0] - 1, 0, imageData.GetDimensions()[1] - 1, 0, imageData.GetDimensions()[2] - 1); voi.SetSampleRate(1, 1, 1); opacityTransferFunction = vtkPiecewiseFunction.New(); range = imageData.GetScalarRange(); opacityTransferFunction.AddPoint(100, 0.0); opacityTransferFunction.AddPoint(1000, 1); //opacityTransferFunction.AddPoint(range[0] + (range[1]-range[0])/2.0, 0.0); //opacityTransferFunction.AddPoint(range[1], 0.7); ////Scale the image between 0 and 1 using a lookup table //vtkLookupTable table = vtkLookupTable.New(); //table.SetValueRange(0,1); //table.SetSaturationRange(0,0); //table.SetRange(range[0], range[1]); //shoul here not be the minimum/maximum possible of "data"? //table.SetRampToLinear(); //table.Build(); //vtkImageMapToColors color = vtkImageMapToColors.New(); //color.SetLookupTable(table); //color.SetInputConnection(imageData.GetProducerPort()); vtkColorTransferFunction ColorTransferFunction = vtkColorTransferFunction.New(); ColorTransferFunction.AddRGBPoint(20.0, 0.0, 0.0, 1.0); ColorTransferFunction.AddRGBPoint(255.0, 1.0, 0.0, 0.0); //ColorTransferFunction.AddRGBPoint(1000.0, 0.8, 0.5, 0.0); //opacityTransferFunction.ClampingOff(); volumeProperty = vtkVolumeProperty.New(); volumeProperty.SetColor(colorTransferFunction); volumeProperty.SetScalarOpacity(opacityTransferFunction); volumeProperty.SetInterpolationTypeToLinear(); volumeProperty.ShadeOn(); volumeProperty.SetAmbient(0.6); volumeProperty.SetDiffuse(0.6); volumeProperty.SetSpecular(0.1); //volumeProperty.SetAmbient(0.1); //volumeProperty.SetDiffuse(0.9); //volumeProperty.SetSpecular(0.2); //volumeProperty.SetSpecularPower(10.0); //volumeProperty[band].SetScalarOpacityUnitDistance(0.8919); vtkVolumeTextureMapper3D volumeTextureMapper = vtkVolumeTextureMapper3D.New(); ////volumeTextureMapper.SetInputConnection(color.GetOutputPort()); volumeTextureMapper.SetInputConnection(voi.GetOutputPort()); //vtkVolumeRayCastCompositeFunction compositeFunction = vtkVolumeRayCastCompositeFunction.New(); //vtkVolumeRayCastMapper volumeMapper = vtkVolumeRayCastMapper.New(); //volumeMapper.SetVolumeRayCastFunction(compositeFunction); //volumeMapper.SetInputConnection(voi.GetOutputPort()); vtk_volume = vtkVolume.New(); vtk_volume.SetMapper(volumeTextureMapper); vtk_volume.SetProperty(volumeProperty); vtk_volume.PickableOff(); vtk_volume.SetPosition(Pos.X, Pos.Y, Pos.Z); }
public void SetInputData(vtkImageData VTKData) { // base.Title += ": " + InputVolume.Name; this.ListVTKData.Add(VTKData); }
public void Generate(CImage3D BinarySubImageSeq, Color Colour, cPoint3D Pos) { vtkImageData ImageData1 = new vtkImageData(); ImageData1.SetDimensions(BinarySubImageSeq.Width, BinarySubImageSeq.Height, BinarySubImageSeq.Depth); ImageData1.SetNumberOfScalarComponents(1); //ImageData1.SetSpacing(BinarySubImageSeq.XResolution, BinarySubImageSeq.YResolution, BinarySubImageSeq.ZResolution); ImageData1.SetScalarTypeToFloat(); vtkFloatArray array1 = new vtkFloatArray(); for (int i = 0; i < BinarySubImageSeq.ImageSize; i++) array1.InsertTuple1(i, BinarySubImageSeq.Data[i]); ImageData1.GetPointData().SetScalars(array1); vtkExtractVOI VOI = new vtkExtractVOI(); VOI.SetInput(ImageData1); VOI.SetSampleRate(1, 1, 1); vtkMarchingCubes ContourObject = vtkMarchingCubes.New(); vtk_PolyDataMapper = vtkPolyDataMapper.New(); //ContourActor = new vtkActor(); VOI.SetVOI(0, BinarySubImageSeq.Width - 1, 0, BinarySubImageSeq.Height - 1, 0, BinarySubImageSeq.Depth - 1); ContourObject.SetInput(VOI.GetOutput()); ContourObject.SetValue(0, 0.5); vtkAlgorithmOutput AlgoOutPut = null; vtk_PolyData = ContourObject.GetOutput(); AlgoOutPut = ContourObject.GetOutputPort(); vtk_PolyDataMapper.SetInput(vtk_PolyData); vtk_PolyDataMapper.ScalarVisibilityOn(); vtk_PolyDataMapper.SetScalarModeToUseFieldData(); vtkActor TmpActor = vtkActor.New(); TmpActor.SetMapper(vtk_PolyDataMapper); TmpActor.SetPosition(Pos.X, Pos.Y, Pos.Z); //Console.WriteLine("PosX"+Pos.X+" PosY"+Pos.Y+" PosZ"+Pos.Z); #region deal with the containers this.Position = new cPoint3D(Pos.X, Pos.Y, Pos.Z); this.Colour = Colour; CreateVTK3DObject(1); // vtk_PolyData = ContourObject.GetOutput(); // compute convex hull hullFilter = vtkHull.New(); hullFilter.SetInputConnection(AlgoOutPut); hullFilter.AddRecursiveSpherePlanes(1); hullFilter.Update(); // this.BackfaceCulling(false); Information = new cInformation(AlgoOutPut, this, hullFilter); #endregion }
protected void Dispose(bool disposing) { if (!_disposed) { if (disposing) { if (_cachedVtkVolume != null) { _cachedVtkVolume.GetPointData().Dispose(); _cachedVtkVolume.Dispose(); _cachedVtkVolume = null; } } // This should have been taken care of by caller of Obtain, release here just to be safe. ReleasePinnedVtkVolume(); _volumeDataInt16 = null; _volumeDataUInt16 = null; _disposed = true; } }