I wrote a matlab code that reads images from folder(images are in RGB). It reads the image one by one. After reading the first image it re-sizes it and then reshapes it so that the new image dimension is (any number of rows X 3 volumes) using this function:
Vectrgb = reshape(rgb,[],3);
Then the code will read a new image.
How should I append the matrix of the second image to the one?
Below is the code:
Folder = 'fo\';
Files = dir([Folder, '\*.png']);
Y=[];
for i = 1 : length(Folder)
name = strcat('telo-phase\',Files(i).name);
image = imread(name);
rgb = imresize(image, 0.50); % resize the image
Vectrgb = reshape(rgb,[],3);
end
Vectrgb1 = Vectrgb';[ind2,ctrs2]= kmeans(double(Vectrgb1),2);
If you wat Y to be the concatanation of all RGB vectors of all images you need to add this line inside the loop
Y = cat( 1, Y, Vecrgb );
PS,
When dealing with filenames and paths it is a good practice to use fullfile command:
Files = dir( fullfile( Folder, '*.png' ) );
Makes your code platform independent.
Related
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');
I am stuck on something that is supposed to be so simple.
I have a folder, say main_folder with four sub folders, say sub1, sub2, sub3 and sub4 each containing over 100 images. Now am trying to read and store them in an array. I have looked all over the internet and some MATLAB docs:
here, here and even the official doc.
My code is like this:
folder = 'main_folder/**'; %path containing all the training images
dirImage = dir('main_folder/**/*.jpg');%rdir(fullfile(folder,'*.jpg')); %reading the contents of directory
numData = size(dirImage,1); %no. of samples
arrayImage = zeros(numData, 133183); % zeros matrix for storing the extracted features from images
for i=1:numData
ifile = dirImage(i).name;
% ifolder = dirImage(i).folder;
I=imread([folder, '/', ifile]); %%%% read the image %%%%%
I=imresize(I,[128 128]);
...
If I try the code in the above snippet, the images are not read.
But if I replace the first two lines with something like:
folder = 'main_folder/'; %path containing all the training images
dirImage = dir('main_folder/sub1/*.jpg'); %rdir(fullfile(folder,'*.jpg'));
then all images in sub1 are read. How can I fix this? Any help will be highly appreciated. I want to read all the images in the four sub folders at once.
I am using MATLAB R2015a.
I believe you will need to use genpath to get all sub-folders, and then loop through each of them, like:
dirs = genpath('main_folder/'); % all folders recursively
dirs = regexp(dirs, pathsep, 'split'); % split into cellstr
for i = 1:numel(dirs)
dirImage = dir([dirs{i} '/*.jpg']); % jpg in one sub-folder
for j = 1:numel(dirImage)
img = imread([dirs{i} '/' dirImage(j).name]);
% process img using your code
end
end
Here i am sharing one of my data which are in .dat file. I have 16162 different files. I merged all into one file and want to read it in matlab and need to extract three parameter's values from a single file and arrange them in either row wise or column wise. I can do it by using C sharp codes but i want to do it by using matlab. can anybody help me out for writing the codes please?
Here is the one sample file data:
DISTRIBUTION: monomodal log-normal
n : 1.000
r_mod: .010
sigma: 1.400
number conc., surface. conc., volume conc.
.1087E+01 .1866E-02 .7878E-05
part. ave. radius, surf. ave. radius, vol. ave. radius :
.1149E-01 .1169E-01 .1201E-01
surface mean radius, volume mean radius :
.1267E-01 .1392E-01
eff. variance :
.9939E-01
Let's say: I want to extract or read three parameters (r_mod, sigma, Surface means radius). The corresponding values for these three parameters from the file I put in this page is .010 , 1.400 , .1267E-01
The output should be (Which i want):
r_mod sigma surface mean radius .01 1.4 1.27E-02 .02 1.4 2.67E-02 .03 1.4 3.98E-02 ... .. .. .. .. .. .. .. ..
I have more than thousands similar files in a same directory. I want to read all those files in matlab and the output should show in this way in a single file.
Given that all files have the exact same structure, the following will do the job (just make sure to ream the comments in the code, you will need to adapt your file names and number of files to read):
n = 2; % Number of files you want to go through
vals = zeros(1,3*n);
str = 'r_mod sigma surface mean radius ';
k = 1;
for i = 1:n
path = ['myFile',num2str(i),'.dat']; % change this to fit your file names
fid = fopen(path, 'rb');
data = textscan(fid,'%s');
fclose(fid);
data = data{1};
vals(k) = str2double(data{8});
vals(k+1) = str2double(data{10});
vals(k+2) = str2double(data{40});
k = k+3;
end
out = [str, num2str(vals)];
fid = fopen('output.txt', 'w');
fprintf(fid,out);
The file output.txt now contains your desired line. You may change the format if you want the output file to be .dat as well.
I have a folder that has various images I am trying to read images in a loop from folder one by one using imread command, any suggestion how to do it best
Thanks
You can use the dir function to get all files inside a directory. This will return a vector of structs which also includes the filenames
loop over all structs
check if file is an image (check e.g. extension)
read image
You have to synchronize your image names to read in a loop. They have to be like image1.jpg, image2.jpg, image3.jpg... You have 10 images like this.
NumberOfimages=10; %chose the number of images you want to give input
prefix_image='image'; %change the desired input image name here only
fileformat='.jpg'; %change the desired input image format here only
for num=1:NumberOfimages
image = imread(strcat(prefix_image,num2str(num),fileformat));
end
well this function will help you to read many images at once even with diferent names:
First put all your images in a folder for example: D:/lab/
they must be in the same format for example: tif
to call the function you type :
A=imread_many( );
and all the images will be in the variable A
if you want the first image you type A{1} if u want the second u type A{2} ..etc
function [ A ] = imread_many( )
srcFiles = dir('D:\lab\*.tif'); % the folder in which ur images exists
for i = 1 : length(srcFiles)
filename = strcat('D:\lab\',srcFiles(i).name);
A{i} = imread(filename);
figure, imshow(A{i});
end
end
srcFiles = dir('C:\Users\Omm\Downloads\multicharacterrec\*.png'); % the folder in which ur images exists
for i = 1 : length(srcFiles)
filename = strcat('C:\Users\Omm\Downloads\multicharacterrec\',srcFiles(i).name);
I = imread(filename);
figure, imshow(I);
This can Help !
S = struct2cell(dir('*.jpg'));
FileNames = S(1,:);
lenDb = length(FileNames);
result= struct('img', {});
for j = 1 : lenDb
result(j).img = imread(FileNames{j})
end
All the images are in struct "result.img"
To have access just call result(NUM).img
Ex:
image(result(1).img)
I have a ton of data that needs to be processed from lab work. I have a ton of .mat files that contain a signal matrix of dimensions 7 x w. I need to resize the matrix to 7 x N and w is larger and smaller than N to make the rest of the analysis easier (don't care about data past N). I have the psuedocode of how I want this to work but don’t know how to implement it. Any help would be great thanks!
Folder structure of all my data:
Main folder
Alpha 1
1111.mat
1321.mat
Alpha 2
1010.mat
1234.mat
1109.mat
933.mat
Alpha 3
1223.mat
etc.
Psudeocode:
Master_matrix = []
For all n *.mat
Load n'th *.mat from alpha 1
If w > N
Resize matrix down to N
Else
Zero pad to N
End if
Master_matrix = master_matrix .+ new resized matrix
End for
rest of my code...
First you need to generate the file list. I have my own function for that, but there is, for example, GETFILELIST or the excellent interactive UIPICKFILES to generate the list of files.
Once you have the file list (I'll assume it's a cell array containing the filenames), you can do the following:
nFiles = length(fileList);
Master_matrix = zeros(7,N);
for iFile = 1:nFiles
%# if all files contain a variable of the same name,
%# you can simplify the loading by not assigning an output
%# in the load command, and call the file by
%# its variable name (i.e. replace 'loadedData')
tmp = load(fileList{iFile});
fn = fieldnames(tmp);
loadedData = tmp.(fn{1});
%# find size
w = size(loadedData,2);
if w>=N
Master_matrix = Master_matrix + loadedData(:,1:N);
else
%# only adding to the first few columns is the same as zero-padding
Master_matrix(:,1:w) = Master_matrix(:,1:w) = loadedData;
end
end
Note: In case you don't actually want to add up the data, but simply store it in the master array, you can make Master_matrix into a 7-by-N-by-nFiles array, where the nth plane of Master_matrix is the content of the nth file. In this case, you'd initialize Master_matrix as
Master_matrix = zeros(7,N,nFiles);
and you'd write the if-clause as
if w>=N
Master_matrix(:,:,iFile) = Master_matrix(:,:,iFile) + loadedData(:,1:N);
else
%# only adding to the first few columns is the same as zero-padding
Master_matrix(:,1:w,iFile) = Master_matrix(:,1:w,iFile) = loadedData;
end
Also note that you might want to initialize Master_matrix as NaN instead of zeros, so that the zeros don't affect subsequent statistics (if that's what you want to do with the data).