Matlab imageset method order of read and name of image? - matlab

%% Load images from folder
% Use imageSet to manage images stored in multiple folders
imset = imageSet('pet_images','recursive');
% Preallocate arrays with fixed size for prediction
imageSize = cnnModel.net.normalization.imageSize;
trainingImages = zeros([imageSize sum([imset(:).Count])],'single');
% Load and resize images for prediction
for ii = 1:numel(imset)
for jj = 1:imset(ii).Count
imshow(read(imset(ii),jj));
trainingImages(:,:,:,jj) = imresize(single(read(imset(ii),jj)),imageSize(1:2));
end
end
I want to read images from a directory. But it gives me error some images.
Assignment has fewer non-singleton rhs dimensions than non-singleton subscripts
I use breakpoint to find which image has a problem. When it gives error, I catch the index of the image and show this image.
I find this image from this directory. it's order is 1061 (orders according to name) but value of jj is 1012.
I have three Question.
Why it gives this error? (The resolution of (error) image :
(263x380))
In order to find the image, I check with the image and same type
cats. In for loop, Can I got the name of this image.?
While imageset read the directory, what according to read it
(name,type,date, etc...)? Why the row number (1061) and index(1012)
are mismatches?

if the image is grayscale, it gives error.
Because rgb image is expected by trainingImages array.
getting the name of image, you can use code below;
imshow(read(imset(ii),jj));
a = select(imset(ii),jj);
str = cellstr(a(1,1).ImageLocation);
title(str);
Because imageset orders alphabetically but different way(name) For example.
Directory order : img1, img2, img3,... img9, img10, img11... img20, ...
imageSet read order: img1, img2, img3,... img9, img10, img20... img21, ...

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');

How to read multiple jpg images in matlab [duplicate]

I have certain images in a directory and I want to load all those images to do some processing. I tried using the load function.
imagefiles = dir('F:\SIFT_Yantao\demo-data\*.jpg');
nfiles = length(imagefiles); % Number of files found
for i=1:nfiles
currentfilename=imagefiles(i).name;
I2 = imread(currentfilename);
[pathstr, name, ext] = fileparts(currentfilename);
textfilename = [name '.mat'];
fulltxtfilename = [pathstr textfilename];
load(fulltxtfilename);
descr2 = des2;
frames2 = loc2;
do_match(I1, descr1, frames1, I2, descr2, frames2) ;
end
I am getting an error as unable to read xyz.jpg no such file or directory found, where xyz is my first image in that directory.
I also want to load all formats of images from the directory instead of just jpg...how can i do that?
You can easily load multiple images with same type as follows:
function Seq = loadImages(imgPath, imgType)
%imgPath = 'path/to/images/folder/';
%imgType = '*.png'; % change based on image type
images = dir([imgPath imgType]);
N = length(images);
% check images
if( ~exist(imgPath, 'dir') || N<1 )
display('Directory not found or no matching images found.');
end
% preallocate cell
Seq{N,1} = []
for idx = 1:N
Seq{d} = imread([imgPath images(idx).name]);
end
end
I believe you want the imread function, not load. See the documentation.
The full path (inc. directory) is not held in imgfiles.name, just the file name, so it can't find the file because you haven't told it where to look. If you don't want to change directories, use fullfile again when reading the file.
You're also using the wrong function for reading the images - try imread.
Other notes: it's best not to use i for variables, and your loop is overwriting I2 at every step, so you will end up with only one image, not four.
You can use the imageSet object in the Computer Vision System Toolbox. It loads image file names from a given directory, and gives you the ability to read the images sequentially. It also gives you the option to recurse into subdirectories.

Adding size information of dataset to file name

I have several datasets, called '51.raw' '52.raw'... until '69.raw' and after I run these datasets in my code the size of these datasets changes from 375x91x223 to sizes with varying y-dimensions (i.e. '51.raw' output: 375x45x223; '52.raw' output: 375x50x223, ... different with each dataset).
I want to later save the '.raw' file name with this information (i.e. '51_375x45x223.raw') and also want to use the new dataset size to later reshape the dataset within my code. I have attempted to do this but need help:
for k=51:69
data=reshape(data,[375 91 223]); % from earlier in the code after importing data
% then executes code with dimensions of 'data' chaging to 375x45x223, ...
length=size(data); dimensions.([num2str(k)]) = length; %save size in 'dimensions'.
path=['C:\Example\'];
name= sprintf('%d.raw',k);
write([path name], data);
% 'write' is a function to save the dat in specified path and name (value of k). I don't know how to add the size of the dataset to the name.
Also later I want to reshape the dataset 'data' for this iteration and do a reshape with the new y dimensions value.
i.e. data=reshape(data,[375 new y-dimension 223]);
Your help will be appreciated. Thanks.
You can easily convert your dimensions to a string which will be saved as a file.
% Create a string of the form: dim1xdim2xdim3x...
dims = num2cell(size(data));
dimstr = sprintf('%dx', dims{:});
dimstr = dimstr(1:end-1);
% Append this to your "normal" filename
folder = 'C:\Example\';
filename = fullfile(folder, sprintf('%d_%s.raw', k, dimstr));
write(filename, data);
That being said, it is far better include this dimension information within the file itself rather than relying on the filename.
As a side note, avoid using names of internal functions as variable names such as length, and path. This can potentially result in strange and unexpected behavior in the future.
Update
If you need to parse the filename, you could use textscan to do that:
filename = '1_2x3x4.raw';
ndims = sum(filename == 'x') + 1;
fspec = repmat('%dx', [1 ndims]);
parts = textscan(filename, ['%d_', fspec(1:end-1)]);
% Then load your data
% Now reshape it based on the filename
data = reshape(data, parts{2:end});

Sorting dicom images in Matlab

I am working with lung data sets in matlab, but I need to sort the slices correctly and show them.
I knew that can be done using the "instance number" parameter in Dicom header, but I did not manage to run the correct code.
How can I do that?
Here is my piece of code:
Dicom_directory = uigetdir();
sdir = strcat(Dicom_directory,'\*.dcm');
files = dir(sdir);
I = strcat(Dicom_directory, '\',files(i).name);
x = repmat(double(0), [512 512 1 ]);
x(:,:,1) = double(dicomread(I));
axes(handles.axes1);
imshow(x,[]);
First of all, to get the DICOM header, you need to use dicominfo which will return a struct containing each of the fields. If you want to use the InstanceNumber field to sort by, then you can do this in such a way.
%// Get all of the files
directory = uigetdir();
files = dir(fullfile(directory, '*.dcm'));
filenames = cellfun(#(x)fullfile(directory, x), {files.name}, 'uni', 0);
%// Ensure that they are actually DICOM files and remove the ones that aren't
notdicom = ~cellfun(#isdicom, filenames);
files(notdicom) = [];
%// Now load all the DICOM headers into an array of structs
infos = cellfun(#dicominfo, filenames);
%// Now sort these by the instance number
[~, inds] = sort([infos.InstanceNumber]);
infos = infos(inds);
%// Now you can loop through and display them
dcm = dicomread(infos(1));
him = imshow(dcm, []);
for k = 1:numel(infos)
set(him, 'CData', dicomread(infos(k)));
pause(0.1)
end
That being said, you have to be careful sorting DICOMs using the InstanceNumber. This is not a robust way of doing it because the "InstanceNumber" can refer to the same image acquired over time or different slices throughout a 3D volume. If you want one or the other, I would choose something more specific.
If you want to sort physical slices, I would recommend sorting by the SliceLocation field (if available). If sorting by time, you could use TriggerTime (if available).
Also you will need to consider that there could also potentially be multiple series in your folder so maybe consider using the SeriesNumber to differentiate these.

Storing two variables image in one variable in matlab

I have an RGB image which I converted into index image using rgb2index. The resultant image is stored in two variable (as matlab requirement). But I want to have it in one variable for further processing. This is what I have tried. The resultant is black.
clc
clear all
close all
%%
I = imread ('Daniel1_SRGB.png');
[in_I,map] = rgb2ind(I,3,'nodither');
imshow (in_I,map)
imwrite (in_I,map,'new_image.PNG','png')
new_I = imread ('new_image.png');
imshow((new_image));
But if do imshow((new_image,map)) it gives me the correct answer. I want it to be independent of variable map.
To convert a indexed image to RGB use:
new_I = ind2rgb(in_I,map)
Not the most elegant solution but this works.
resR = reshape(map(in_I(:)+1,1), size(in_I));
resG = reshape(map(in_I(:)+1,2), size(in_I));
resB = reshape(map(in_I(:)+1,3), size(in_I));
res = cat(3, resR, resG, resB);
imshow(res);
Edit: Modified answer to include rayryeng's improvement.