How to export images in *.dat format in MATLAB - matlab

I want to use the MATLAB findcluster tool (Fuzzy Logic Toolbox), but it requires the data to be loaded to be in *.dat format.
Is it possible to export my grayscale images(2D matrices actually) in *.dat through MATLAB? And if yes, could I also export 3D images the same way?
Thanks in advance for any suggestions,
Ziggy.

The key is to think of the image as just like any other array. Then saving/loading to a .dat file is easy. Here's some sample code:
% Open a sample image
testImage = imread('tire.tif');
figure; imshow(testImage)
% Convert to double so the ASCII conversion will work properly
testImage = double(testImage);
% Save the .dat file
save test.dat testImage -ascii
% Load the .dat file we just saved
testImageReopened = load('test.dat');
% Convert back to the original format
testImageReopened = uint8(testImageReopened);
figure; imshow(testImageReopened);
I believe it should work similarly for a 3D image, but you might want to try it out to be sure.

Related

How to convert .mat to any image format(.png,.jpeg,..jpg, .jpeg, .jfif, .pjpeg, .pjp,.webp, .bmp,.tif, .tiff SVG) using matlab

I have a dataset whose images extension are in .mat. I found a solution in Matlab to solve this issue
Here is an example MATLAB code to convert a .mat file to an image format:
% Load the .mat file
load('example.mat');
% Convert the data to uint8
I = reshape(uint16(linspace(0,65535,25)),[5 5])
example_matrix = im2uint8(I);
% Try to save the image
try
imwrite(example_matrix, 'example.png');
disp('Image saved successfully');
catch
disp('Error saving image');
end
Note that you should replace "example.mat" and "example_matrix" with the actual names of your .mat file and matrix data, respectively. You can also change the format of the output image by changing the file extension in the imwrite function (e.g., 'example.jpg' or 'example.bmp').

pixelLabelDatastore from loaded image in workspace

I have multiple small *.mat files, each containing 4 input images (template{1:4} and a second channel template2{1:4}) and 4 output images (region_of_interests{1:4}), a binarized ('mask') image to train a deep neural network.
I basically followed an example on Mathworks and it suggests to use a function (in this example #matreader) to read in custom file formats.
However ...
It seems impossible to load multiple images from one *.mat file using any load function as it only allows one output, and imageDatastore doen't seem to allow loading data from workspace. How could this be achieved?
Similarly, it seems impossible to load a pixelLabelDatastore from a workspace variable. As a workaround I ended up saving the contents of my *.mat file to an image (using imwrite, saving to save_dir), and re-loading it from there (in this case, the function doesn't even allow to load *.mat files.). (How) can this be achieved without re-saving the file as image?
Here my failed attempt to do so:
%main script
image_dir = pwd; %location of *.mat files
save_dir = [pwd '/a/']; %location of saved output masks
imds = imageDatastore(image_dir,'FileExtensions','.mat','ReadFcn',#matreader); %load template (input) images
pxds = pixelLabelDatastore(save_dir,{'nothing','something'},[0 255]);%load region_of_interests (output) image
%etc, etc, go on to train network
%matreader function, save as separate file
function data=matreader(filename)
in=1; %give up the 3 other images stored in template{1:4}
load(filename); %loads template and template2, containing 4x input images each
data=cat(3,template{in},template2{in}); %concatinate 2 template input images in 3rd dimension
end
%generate example data for this question, will save into a file 'example.mat' in workspace
for ind=1:4
template{ind}=rand([200,400]);
template2{ind}=rand([200,400]);
region_of_interests{ind}=rand([200,400])>.5;
end
save('example','template','template2','output')
You should be able to achieve this using the standard load and save function. Have a look at this code:
image_dir = pwd;
save_dir = pwd;
imds = imageDatastore(image_dir,'FileExtensions',{'.jpg','.tif'});
pxds = pixelLabelDatastore(save_dir,{'nothing','something'},[0 255]);
save('images.mat','imds', 'pxds')
clear
load('images.mat') % gives you the variable "imds" and "pxds" directly -> might override previous variables
tmp = load('images.mat'); % saves all variables in a struct, access it via tmp.imds and tmp.pxds
If you only want to select the variables you want to load use:
load('images.mat','imds') % loads "imds" variable
load('images.mat','pxds') % loads "pxds" variable
load('images.mat','imds','pxds') % loads both variables
EDIT
Now I get the problem, but I fear this is not how it is going to work. The Idea behind the Datastore objects is, that it is used if the data is too big to fit in memory as a whole, but every little piece is small enough to fit in memory. You can use the Datastore object than to easily process and read multiple files on a disk.
This means for you: Simply save your images not as one big *mat file but as multiple small *.mat files that only contain one image.
EDIT 2
Is it strictly necessary to use an imageDatastore for this task? If not you can use something like the following:
image_dir = pwd;
matFiles = dir([image_dir '*.mat']);
for i=1:length(matFiles)
data = load(matFiles(i).name);
img = convertMatToImage(data); % write custom function which converts the mat input to your image
% or something like this:
% for j=1:4
% img(:,:,j) = cat(3,template{j},template2{j});
% end
% process image
end
another alternative would be to create a "image" in your 'matreader' which does not only have 2 bands but to simply put all bands (all templates) on top of each other providing a "datacube" and then in an second step after iterating over all small mat files and reading them splitting the single images out of the one bigger datacube.
would look something like this:
function data=matreader(filename)
load(filename);
for in=1:4
data=cat(3,template{in},template2{in});
end
end
and in your main file, you have to simply split the data into 4 pieces.
I have never tested it but maybe it is possible to return a cell instead of a matrix?
function data=matreader(filename)
load(filename);
data = cell(1,4)
for in=1:4
data{in}=cat(3,template{in},template2{in});
end
end
Not sure if this would work.
However, the right way to go forward from here really depends on how you plan to use the images from imds and if it is really necessary to use a imageDatastore.

How can I convert matlab code to image?

For exmaple,I have the following code.
% Generate random data from a uniform distribution
% and calculate the mean. Plot the data and the mean.
n = 50; % 50 data points
r = rand(n,1);
plot(r)
% Draw a line from (0,m) to (n,m)
m = mean(r);
hold on
plot([0,n],[m,m])
hold off
title('Mean of Random Uniform Data')
for v = 1.0:-0.2:0.0
disp(v)
end
I want to convert MATLAB code to an image.
For example, if you copy the MATLAB code into a software then it return the image like this:
How to do it?
If I use this code and publish it to PDF file,the code is not completely display.
sumLumi(x,y)=LLmap3(floor(x/4)+1,floor(y/4)+1)+LLmap3(floor(x/4)+2,floor(y/4)+1)+LLmap3(floor(x/4)+1,floor(y/4)+2)+LLmap3(floor(x/4)+2,floor(y/4)+2);
From the MATLAB editor you can Publish your document as a PDF (by changing the Output file format to pdf under publishing options). It will also evaluate the code unless you change the Publishing Options>Code Settings>Evaluate code to false.
The PDF can then can converted to an image (a quick google search gives an online PDF to JPG converter).
You can break a line and continue on the next with ..., for example
sumLumi(x,y)=LLmap3(floor(x/4)+1,floor(y/4)+1)+LLmap3(floor(x/4)+2,floor(y/4)+1)+LLmap3(floor(x/4)+1,floor(y/4)+2)+LLmap3(floor(x/4)+2,floor(y/4)+2);
can be written as
sumLumi(x,y) = LLmap3(floor(x/4)+1, floor(y/4)+1) ...
+ LLmap3(floor(x/4)+2, floor(y/4)+1) ...
+ LLmap3(floor(x/4)+1, floor(y/4)+2) ...
+ LLmap3(floor(x/4)+2, floor(y/4)+2);
If you want to use Matlab only you can use this workflow:
Make your code to be single .m file. Any text file will work.
Read this file in cell column vector Code;
Process the lines adding using TeX or LaTeX formatting commands;
Create white figure with text(x,y,Code);
Export the figure.
This might be good way to produce many figures with same style.

How do I extract the TIFF preview from an EPS file using MATLAB?

EPS files can include embedded TIFF (and rarely WMF) previews for easy rendering in environments which do not have PostScript available. (See Wikipedia for more info.)
Given such an EPS, how can I extract the TIFF into a separate file using MATLAB?
% Define the source EPS file and the desired target TIFF to create.
source = 'ode_nonneg1.eps';
target = 'ode_nonneg1.tif';
% Read in the EPS file.
f = fopen(source,'rb');
d = fread(f,'uint8');
fclose(f);
% Check the header to verify it is a TIFF.
if ~isequal(d(1:4),[197;208;211;198])
error 'This does not appear to be a vaild TIFF file.'
end
% Extract the TIFF data location from the headers.
tiffStart = sum(d(21:24).*256.^(0:3)')+1;
tiffLength = sum(d(25:28).*256.^(0:3)');
% Write the TIFF file.
f = fopen(target,'w');
fwrite(f,d(tiffStart:tiffStart-1+tiffLength),'uint8','b');
fclose(f);

Saving image using MATLAB

I made a program in MATLAB to generate images with different specifications, but each time I change one of theses specifications I had to re-save the image under a different name and path. So, I made a for loop to change these specifications, but I don't know how I can make MATLAB save the generated image with different names and different paths...
How can I write a program to make MATLAB save multiple generated images with different names and different paths as a part of for–loop?
Put something like this at the end of your loop:
for i = 1:n
<your loop code>
file_name=sprintf('%d.jpg',i); % assuming you are saving image as a .jpg
imwrite(your_image, file_name); % or something like this, however you choose to save your image
end
If you want to save JPEG, PNG etc., then see #AGS's post. If you want to save FIG files, use
hgsave(gcf, file_name)
instead of the imwrite line. There's also
print('-djpeg', file_name) %# for JPEG file (lossy)
print('-dpng', file_name) %# for PNG file (lossless)
as an alternative for imwrite.
Since I wanted to save the plots in my loop in a specific folder in my present working directory (pwd), I modified my naming routine as follows:
for s = 1:10
for i = 1:10
<loop commands>
end
end
% prints stimuli to folder created for them
file_name=sprintf('%s/eb_imgs/%0.3f.tif',pwd,s(i)); % pwd = path of present working
% directory and s(i) = the value
% of the changing variable
% that I wanted to document
file_name = /Users/Miriam/Documents/PSYC/eb_imgs/0.700.tif % how my filename appears
print('-dtiff', '-r300', file_name); % this saves my file to my desired location
matlab matlab-path