How to convert nii format file into 2D image - matlab

I have a file with .nii extension. I don't know how to convert a .nii file into 2D format.My question is while converting .nii file into 2D, am I losing some information about the file.Which format is good? dicom or png or bmp.
nii = load_nii('im.nii');
size(nii.img);
returns
ans =
39 305 305
and it is in uint8 format
May I use squeeze or resize?How to apply resize to this image;whether it lose information?

Yes you can manipulate the image/sequence as you would with any array.
Here is a simple example with data available from the NIH here.
The data set is in 4D and is named "filtered_func_data.nii".
Let's load the dataset and access the img field of the resulting structure:
S = load_nii('filtered_func_data.nii')
Here, S is a structure with the following fields:
S =
hdr: [1x1 struct]
filetype: 2
fileprefix: 'filtered_func_data'
machine: 'ieee-be'
img: [4-D int16]
original: [1x1 struct]
And we can access the image data with the field img (you already figured that out):
A = S.img
If we check the size, we get:
size(A)
ans =
64 64 21 180
So the dataset consists in 64x64 images with a depth/number of slices of 21 and a number of frames of 180.
At this point we can manipulate A as we like to reshape, resize or anything.
Here is a simple code (animated gif) to loop through each slice of the 1st timepoint in the 4D array:
NumSlices = size(A,3)
figure(1)
filename = 'MRI_GIF.gif';
for k = 1:NumSlices
imshow(A(:,:,k,1),[])
drawnow
frame = getframe(1);
im = frame2im(frame);
[imind,cm] = rgb2ind(im,256);
if k == 1;
imwrite(imind,cm,filename,'gif', 'Loopcount',inf);
else
imwrite(imind,cm,filename,'gif','WriteMode','append');
end
pause(.1)
end
Output:
Which looks pretty nice to me.
So in your case, you get a size of [39 305 305] and you can apply the same manipulations I did to play around with your data set, which is in 3D.
EDIT
With your data it's the same:
S = load_nii('Subject01.nii');
A = S.img;
NumSlices = size(A,3);
And then, if you want a 2D image you need to select a slice in the 3D array.
For example, the first slice is accessed like so:
A(:,:,1)
And so on for the rest.
To save images as png, use imwrite.
Hope that helps!

Related

Save concatenated images in MATLAB

I am trying to concatenate two 256x256 images and save them using imwrite. The saved image is supposed to be 256x512, but when I load the saved image, the size shows to be 343x434x3. How do I solve this?
the code I am using is:
new_name3 = strcat(f_name_image, '\', kk, '_', num2str(ff), '_pair.png');
pair = [orig_im noisy_image]; %concatenating two 256x256 images
imagesc(pair)
f = getframe(gca);
im = frame2im(f);
imwrite(im, new_name3);
Saving the image from the frame can be lossy without configuring additional options. To retain the pixel information save the concatenated image directly from the pair (here Image_Pair) array. Also, the third dimension in 343x434x3 represents the RGB colour channels of the image.
%Grabbing the two images%
Image_1 = imread('Image_1.jpeg');
Image_2 = imread('Image_2.jpeg');
%The file name for the concantenated images%
New_File_Name = "Image_3.jpeg";
%Concatenating the images%
Image_Pair = [Image_1 Image_2];
%Displaying the image pair%
imshow(Image_Pair);
%Saving the image to the "New_File_Name"%
imwrite(Image_Pair, New_File_Name);
%Loading the saved image to see if dimensions are consistent%
Saved_Image = imread('Image_3.jpeg');

read and show raw depth image in matlab

I have a set of .raw depth images. The image format is 500X290 with 32 bytes per pixel. When I open them with IrfanView image viewer I see the depth image correctly like this:
displayed image in IrfanView
Now I want to read and display the same depth image in Matlab. I do like this:
FID=fopen('depthImage.raw','r');
DepthImage = fread(FID,[290,500],'bit32');
fclose(FID);
colormap winter;
imshow(DepthImage);
DepthImage is a 290X500 type double matrix.
what I get from this code is this image:
displayed image in Matlab viewer
when I change fread parameter from 'bit32' to 'bit24' I get this:
displayed image in Matlab with bit24
I guess each element in DepthImage contains 32 bits where each 8 bits corresponds to R,G,B and D values. but how can I read the image correctly and display it like the one in IrfanView?
the raw file: https://drive.google.com/file/d/1aHcRmMKvi5gtodahR5l_Dx8SbK_920c5/view?usp=sharing
There might be an issue with image metadata header, like "date and time of the shot", "camera type". Open your image with notepad++ to check for "date and time". If you upload your original raw image, it will be easier to try things.
Upd: Ok, this is something. Check if it helps
FID=fopen('camera00000000000014167000.raw','r');
DepthImage = fread(FID,290*500*4,'int8');
DepthImageR = DepthImage(1:4:end);
DepthImageG = DepthImage(2:4:end);
DepthImageB = DepthImage(3:4:end);
DepthImageD = DepthImage(4:4:end);
dataR = reshape(DepthImageR, 500,290);
dataG = reshape(DepthImageG, 500,290);
dataB = reshape(DepthImageB, 500,290);
dataD = reshape(DepthImageD, 500,290); % all equal to 64 - useless
figure()
subplot(2,2,1)
image(dataR)
subplot(2,2,2)
image(dataG)
subplot(2,2,3)
image(dataB)
subplot(2,2,4)
data = zeros(500,290,3);
data(:,:,1) = dataR;
data(:,:,2) = dataG;
data(:,:,3) = dataB;
image(data)

Convert a Matrix of doubles to a grayscale .tif image

I have an nCol by nRow matrix of doubles that I want to convert into an nCol by nRow grayscale images of pixels. I don't want to cut this down to an image scaled to 256 channels. I'd be happy with using singles instead of doubles. I've looked through the Tiff class documentation from Mathworks but can't find a simple example for this.
I tried to read about Tiff class and yep it is very poor documented. But I found this going through trial and error:
lets say we have matrix
data = rand(100,200);
Lets save it as Tiff:
t = Tiff('new.tif','w') %create object of Tiff class
setTag(t,Tiff.TagID.ImageLength,size(data,1)) %define image dimentions
setTag(t,Tiff.TagID.ImageWidth,size(data,2))
setTag(t,'Photometric', Tiff.Photometric.MinIsBlack) %define the color type of image
%specifies how image data components are stored on disk
setTag(t,'PlanarConfiguration',Tiff.PlanarConfiguration.Chunky);
setTag(t,'BitsPerSample',64); %because 1 double = 8byte = 64bits
%Specify how to interpret each pixel sample (IEEEFP works with input doubles)
setTag(t,'SampleFormat',Tiff.SampleFormat.IEEEFP);
t.write(data)
t.close
Lets test this now:
datac = imread('new.tif')
whos datac
Name Size Bytes Class Attributes
datac 100x200 160000 double
And:
datac(:,1)
ans =
0.4921
0.6908
0.1544
0.4433
...

How can I imwrite a double in Matlab?

I am producing 3500x7500 size double matrices in a loop that I want to export as tif files.
A section of the code
for k = 1:length(basinlist{1})
#some operation that produces GRID
imwrite(GRID,filename);
end
But, when I do this, the TIF file produced contains only 255 and output is in uint8. I read about it in the documentation, but I am not able to fix it. All I want is to retain the original values with no scaling or anything.
If this helps:
>> max(max(GRID))
ans =
1.5646e+04
>> min(min(GRID))
ans =
1.1119e+03
Suppose we want to create image with such colour depth that will fit to given data.
Data exported to image format are converted to uint8 by default (data range 0-2^8-1).
But Matlab (2011b) can operate with more uintX formats where X stands for X bits per value.
uint8 with span 0-255 (2^8)
uint16 with span 0-65 535 (2^16)
uint32 with span 0-4.29 e 9 (2^32)
uint64 with span 0-1.84 e 19 (2^64)
Code to export data without any loss:
for k = 1:length(basinlist{1})
#some operation that produces GRID
%% Convert GRID to roughest acceptable uint format
GRID=uint16(GRID);
%% Export
imwrite(GRID,filename);
end

reading and writing mulltiple images automatically in matlab?

i have 250 images stored at
E:\HandVein_DataSet
these 250 images belong to 50 person , this mean each one has 5 images
these pictures are arranged as following
0001hv1-0001hv2-0001hv3-0001hv4-0001hv5 ....0002hv1-0002hv2-0002hv3-0002hv4-0002hv5 until 0050hv1-0050hv2-0050hv3-0050hv4-0050hv5
I want to read all these images and processing them according my steps and then saved the resultant images after preproceesing in a specific file,for example at E:\final result.
How can i do this in matlab?
I'm assuming that the filenames are, e.g., 0001hv1.jpg (you can change the extension as necessary). You don't say what the output is; I'm assuming it's a modified version of the input image and that you want to use the same naming scheme.
in_dir = 'E:/Hand/Vein_DataSet';
out_dir = 'E:/final\ result';
for px = 1 : 50,
for hx = 1 : 5,
fname = sprintf('%04dhv%d.jpg', px, hx);
current_image = imread(fullfile(in_dir, fname));
% do processing
out_image = some_function(current_image);
% save output
imwrite(out_image, fullfile(out_dir, fname));
end
end