Get Array from Nifti File using PyVista - arrays

im new to programming and im working with a MRI dataset (.nii) in PyVista
Im trying read the Nifti File and extract an array so i can compare two MRIs based on the differences in the array and visualise it with PyVista.
PyVista is mostly based on the VTK library so maybe there is a function in VTK but im a bit helpless looking through the Docs.
I found a solution in nibabel to access an array:
img = nib.load(example_filename)
a = np.array(img.dataobj)
But with that i still can't access the PyVista Array to highlight the differences.
Thank you for your help in advance!

We need to perform two distinct operations:
retrieving the intensity values from your NIfTI dataset using, for instance, nibabel
plotting the 3D numpy array using, for instance, PyVista. Take a look at the PyVista documentation here and here for further details. You will have to add origin, spacing, etc. but for the sake of simplicity I am going to omit them.
Here is the code:
import nibabel as nb
example = nb.load("/nifti/path/example.nii.gz")
intensities = example.get_fdata()
grid = pv.UniformGrid()
grid.dimensions = np.array(values.shape) + 1
grid.cell_data["intensities"] = intensities.flatten(order="F")
grid.plot(volume=True, cmap="bone")

Related

Issue with writeVideo/ VideoWriter MATLAB

I'm a beginner so sorry in advance for the mistakes.
I have a set of data from a camera recording saved in a 4D array with these dimensions (250x300x10603x12).
The first is the dimensions of the video (pixels). The 10603 are the FrameRatexTime. 12 are the subjects I recorded.
I extract one subject at a time for analysis in this way:
subj1 = data(:,:,:,1);
This brings me to an array containing the frames of subject 1, which I can display with implay.
Now I would like to write a video of this new array and save it in .avi format, I use this code:
v = VideoWriter('subj1.avi')
open(v)
writeVideo(v,subj1)
close(v)
but it keeps giving me this error
Error using VideoWriter/writeVideo (line 410) IMG must be an array of
either grayscale or RGB images.
In fact, looking at the shape of the array, there is nothing that points to a grayscale or RGB index. How can I get a .avi file in this case? Do I have to transform the array?
Why does it still display the video with implay?
clarification: the fact that I have to transform the array into an .avi file is because I will have to analyse it by exporting it to Python with OpenCv.
In fact, if I export the .mat file directly to Python, I can't get the list of Frames.
Matlab's documentation for writeVideo says that for a sequence of grayscale images like you have, it is expecting a "height-by-width-by-1-by-frames" array. You are only passing it "height-by-width-by-frames".
So, you need to reshape your subj1. Maybe try doing it like this:
newsubj = zeros(250, 300, 1, 10603)
newsubj(:,:,1,:) = subj1
and then save newsubj instead of subj1:
writeVideo(v,newsubj)
Finally, I think you may get some lossy compression when you save as an avi, so it may not be the best way to export it from Matlab and importing it to Python.

Function similar to vlookup: Why doesn't my indexOf work?

If I would like to match the word that I need to find it the same as <lookup> in Excel. I intend to create a form for Example. I have a file certain big data and I will create a box for fill in data that you need then Enter it show the Description of data. Now I got stuck I don't know how to write to the script I have learned in youtube but don't have a solution that nearby with my need it nearby just <Indexof> function.
var data = Activesheet.getRange(1,1,Activesheet.getLastRow()-1,1).getValues();
Logger.log(data.indexOf("TPBSA"));
data is a 2D(two dimensional) array. indexOf only works with a 1D array. flatten the array before indexOf:
const data = [["A1"],["A2"],["TPBSA"],["A4"]];
console.info(data.flat().indexOf("TPBSA"));
//or
console.info(data.findIndex(e=>e[0]==='TPBSA'))

How to create Datasets Like MNIST in Pytorch?

I have looked Pytorch source code of MNIST dataset but it seems to read numpy array directly from binaries.
How can I just create train_data and train_labels like it? I have already prepared images and txt with labels.
I have learned how to read image and label and write get_item and len, what really confused me is how to make train_data and train_labels, which is torch.Tensor. I tried to arrange them into python lists and convert to torch.Tensor but failed:
for index in range(0,len(self.files)):
fn, label = self.files[index]
img = self.loader(fn)
if self.transform is not None:
img = self.transform(img)
train_data.append(img)
self.train_data = torch.tensor(train_data)
ValueError: only one element tensors can be converted to Python scalars
There are two ways to go. First, the manual. Torchvision.datasets states the following:
datasets are subclasses of torch.utils.data.Dataset i.e, they have __getitem__ and __len__ methods implemented. Hence, they can all be passed to a torch.utils.data.DataLoader which can load multiple samples parallelly using torch.multiprocessing workers.
So you can just implement your own class which scans for all the images and labels, keeps a list of their paths (so that you don't have to keep them in RAM) and has the __getitem__ method which given index i reads the i-th file, its label and returns them. This minimal interface is enough to work with the parallel dataloader in torch.utils.data.
Secondly, if your data directory can be rearranged into either structure, you can use DatasetFolder and ImageFolder pre-built loaders. This will save you some coding and automatically provide support for data augumentation routines from torchvision.transforms.

Meshroom: how to access the final camera parameters?

I am trying to write a script which loads the camera parameters from Meshroom and imports them into a CAD program. My first understanding was that these parameters (position, rotation matrix, focal length etc.) are contained in the JSON-file cameras.sfm in the StructureFromMotion-subdirectory.
After importing these parameters into Rhino3D and comparing the resulting views onto the 3D-mesh with the undistorted photographs in the PrepareDenseScene-directory, I find surprising large discrepancies. The mesh which was the result of the run was good, so I think that the deviation is because of the parameters in cameras.sfm being not the final ones. This assumption is also supported by the fact that the file only contains the focal length as read from the input images' EXIF information and no refined values. So my question is:
How can I access the final camera parameters from the output of Meshroom?
Knowing this would help me a lot for re-building a photogrammetry/CAD pipeline I had previously implemented for VisualSFM + CMPMVS.
Many thanks!
EDIT: As this is my first post, I am not able to create a new tag for Meshroom. Perhaps this could be added by someone else? Thanks!

Easy way to plot and display arrays?

First post here. Using C in Visual Studio 2008. Can work with VS 2005 if necessary.
How do I display numerical data in arrays as in a spreadsheet?
How do I plot numerical data in arrays?
These seem to be simple questions. But I cannot find solutions. So far, I would print the data to a file, import into Excel and view/plot. However, with this code there are too many arrays--so the print/import/plot is tiring.
Some constraints.
I do not want to write 20+ lines of code to do the above. MATFOR or Array Visualizer let you do the plotting with a one line function call.
They cannot display the data in a convenient format. I would like to display the data and the plot in one or two windows so that they are visible simultaneously.
This is a win32 console application---all the code is portable.
Will be using these during debugging.
Free or paid.
While I am looking for something specific, the requirements are substantially the same for any one doing numerical work with arrays and matrices--displaying data and plot simultaneously.
I am hoping that a such a tool has been written and is available.
I am also open to a solution that outputs the array data to an Excel sheet (can keep Excel open) and if it can also plot that can be great but I can live without plotting.
PS: I need this only when debugging the code.
I use ArrayDebugView which is a plug-in you install in Visual studio and draws graphs out of arrays while you are debugging your application. It works as a visual way of variable watch in debug mode. You don't need to write a line of code.
I can't think of any library that would enable what you want in a console app in less than 20 lines of code. My suggestion would be instead to script the plotting-step using MATLAB og GNU Octave to do the actual plotting.
In order to display numerical data in array, you should add the pointer to the first data element you want to observe, into the watch --- if you want to observe the array from the beginning, it would just be the array name, which is the pointer to the first element. In order to view more then one element, you add a "," after the pointer, followed by the number of element you want to observe.
For example, in order to observe the elements of float farray[100];, you should add to the watch farray,100.
In order to plot, you can copy-paste from the watch to your plotting software (i.e. excel), but it is not very convenient as you cannot copy the data column alone, but the columns to the left and right as well, so it involves extra manual editing.
I use GNUPlot (http://www.gnuplot.info/) to display my performance/speedup measurements.
I print my numbers to stdout and wrote a bash script that combines these numbers and calls gnuplot for rendering.
I made a simple plotting program for that purpose. There is only a textbox where I paste the data and a chart where it's drawn.
The data needs to be in either form:
with an automatic X (increment by 1 for each value): seriesName value
for both X and Y specified: seriesName xvalue yvalue
Most of the time I used to plot data from tracepoints.
I copy/paste the whole output window of VS, the plotting program ignores anything that doesn't follow these 2 forms (so I don't have to cleanup the string and put it in excel and all).
It does line, point, colum, area charts and save image, copy to clipboard.
MiniPlot
There are several ways to do this but this will require writing some code. Visualizing data is generally easy and straight forward but visualizing data exactly the way you want them to look will require some additional code and work.
There are several options to visualize data:
A combination of BASH and GNUPLOT
Use MATLAB or OCTAVE for all your calculations and visualization
Use PYTHON and SciPy and matlibplot libraries.
Gnuplot is a great tool to plot data but it is cumbersome to use. It looks fabulous if you invest time to get the plots right and combines excellent with LaTeX and has a good fit implementation for arbitrary functions. Visit http://gnuplot-tricks.blogspot.ch/ great site to learn all about gnuplot.
Numerical programs such as MATLAB and it's open source equivalent OCTAVE are great because they are fast implementation languages for numerical programs and have extensive additional libraries especially MATLAB. For high load numerical computing it is really slow and the plot library is only good for basic plotting needs.
Using PYTHON and its scientific programing libraries (SciPy and matlibplot) are a great combination. This allows excellent plot which are not as cryptic as gnuplot to plrogram and it is more flexible than MATLAB in plotting. Additionally it gives you a environment for numerical programing like MATLAB.

Resources