How can I save set of altered images in new folder in MATLAB? - matlab

I have folder that consists of 10 images.
I am trying to apply a gaussian filter to each of them. I read images from a folder named dd and then I want to save the altered images in newfolder. However, when I look at the image it is empty.
How can I do this in correct way , read 10 images , filter them , save altered 10 images in new folder.
Here is the code that I have so far:
for img = 1:10
a = imread(['\dd\',int2str(img),'.pgm']);
G = fspecial('gaussian',[3 3],2);
Ig = imfilter(a,G,'same');
imshow(Ig);
imwrite( Ig, 'Ig.pgm '); % does not work !!
save ([ path,'\newfolder\', 'new.pgm'],'Ig');% it save empty image !!!
end

save is not for saving images. Instead, you will want to use imwrite for that. You will also want to provide the full path to imwrite and here we use mat2gray just to ensure that your data covers the entire dynamic range of the image type. You'll also want to be sure that each output image has a unique name so that they don't overwrite one another.
output_filename = fullfile(path, 'newfolder', sprintf('%d_new.pgm', img));
imwrite(mat2gray(Ig), output_filename, 'pgm');
As a side note, you'll want to use fullfile to reliably construct your folder paths across computers and operating systems.

Related

How to automatically save the output image file in a specified folder?

I am using Canny edge detection on images. Since my original 10 images are in the path folder, C:\Users\X\Desktop\FoodRGB as 01.jpg, 02.jpg, 03.jpg and so on, I want to save all my output images in the folder C:\Users\X\Desktop\FoodCanny as 01.jpg, 02.jpg, 03.jpg.
I figured that I have to use imwrite() function to write the output images in a specific folder but I am not sure about the big idea.
The following code I am using is saving the images as 0%d.jpg in FoodCanny Folder I manually created.
for k = 1:10
img = sprintf('C:\Users\X\Desktop\4\Food Canny\0%d.jpg',k);
imwrite(canny_image, 'C:\Users\X\Desktop\4\Food Canny\0%d.jpg');
end
Supposing you want to get canny edges of all screenshots in the C:\Users\Asus\Pictures\Screenshots and save them to the other folder D:\. You can do this by :
clc;clear all;
fpath = fullfile('C:\Users\Asus\Pictures\Screenshots','*.png');
img_dir = dir(fpath);
for k=1:length(img_dir)
input_image=strcat('C:\Users\Asus\Pictures\Screenshots\',img_dir(k).name);
original = rgb2gray(imread(input_image));
original= edge(original,'canny');
imwrite(original,strcat('D:\',sprintf('edge(%d).jpg',k)));
end

Create a list (or array) of images in MATLAB

This could be very simple, but I have been looking for the proper answer for hours.
I am working on a visual task for primates and am using the PsychToolbox in MATLAB. What I am currently trying to do is randomize the photo that the subject has to decide on. There are many code examples for randomly picking images from a directory, but the images I am using have already been imported because they were previously used.
For reference here is the code that I have used to import the images randomly from the directory on my computer:
% Get the image files for the experiment
imageFolder = [cd '/ALSAMultiracial/'];
imgList = dir(fullfile(imageFolder, '*.jpg'));
numImages = length(imgList);
numTrials = numImages;
% Generate a random number between 1 and the number of images
randomNumber = randperm(numImages, 1);
% Get corresponding name of the image
randomImage = imgList(randomNumber).name;
% Now load the image
theImage = imread([imageFolder randomImage]);
% Make the image into a texture
tex = Screen('MakeTexture', window, theImage);
% Draw the texture
Screen('DrawTexture', window, tex, [], [], 0);
In this task, I flip between two images: theImage and theImage2. After I do that, I want to choose a random image to show: theImage or theImage2. What I was thinking is that I could make a list or an array and do something similar to what I did previously, but the problem is that I have unsuccessfully tried to make a list and array of these images to repeat the process, but it has not worked. For reference, all of the images in question are jpg and the same size.
Your help is very appreciated.
If you're just trying to load up a whole directory of pictures into an array, I'd suggest using a for loop over your imgList to read all of your images into an array. That way, when you generate your random number, you can just reference an array index.
Something to keep in mind with this. when imread is called, it's going to return a 3D array (red green blue values) So when you read in multiple images, you're going to have a 4D array.
You can do something like:
clear pictureData;
clear imgList;
for imgList = dir(fullfile(imageFolder, '*.jpg'))
pictureData(i, :, :, :) = imread([imageFolder imgList]);
end
to read in all of your pictures. Then when you grab a random number, you can grab the specific jpeg data you want with
pictureData(randomNumber,:,:,:)
Let me know if this is clear or not, I can try to explain further if you have specific questions, or if I've missed the mark completely.
Welcome to Stack Overflow. :)

Being able to read images from any directory

I'm new to Matlab and I am having some problems with reading images and dealing with directories and things like that. I had an assignment where I was to write a script that converts an image that is not grayscale into grayscale (for example, if the image is truecolor, convert to grayscale).
This was my code:
img = uigetfile('*');
imgx = imfinfo(img);
imgx.ColorType
if imgx.ColorType == 'truecolor'
img = imread(img);
img = rgb2gray(img);
end
However, I ended up getting points off for the following:
"only works if image is in the same folder as script"
I realize that my script only works for images that are in folders that are on the MATLAB path, so I don't know if that's a separate issue from what he said or if that's what he meant. I assume he wants to be able to select any image on your computer to be able to read and perform the operation, but I don't know how to approach this. Can anyone help me?
The problem is that img = uigetfile('*') returns only the file name as string. To work with pictures in folders other than matlab folder you would need to extract the full path. You can do this using the following approach:
[fileName, folderName] = uigetfile('*');
img=fullfile(folderName, fileName);
imgx = imfinfo(img);
The rest of your code should work after this small change

Save image from imshow

I want to save the image to a file after doing imshow(im,[]); to display it later in GUI. I am trying the following code, but it doesn't work.
New= imshow(uint8(MHI{t}),[]);
imwrite(New,'TMHI.jpg','jpg')
Any help will be appreciated. Thank you.
The imshow function is only used to show the image in MATLAB. If you want to save it, you don't need the imshow at all. And: the value (New) returned by imshow() is the handle to the figure. You need that handle if you want to modify how the figure is shown on the screen.
To write the image to the disk, you only need the imwrite function, which has the syntax:
imwrite(A,filename)
where A is the image array.
If the file name ends with .jpg, then MATLAB will create a JPEG image by default, so you don't need to specify that. (But of course, you still can.)
But before saving: you have a problem with the normalization of the image. MATLAB assumes that a double image is scaled to [0,1] and that a uint8 image is scaled to [0,255]. With imshow(im,[]) you override these defaults and make MATLAB calculate new values. You will experience the same problem when saving. The solution is to normalize the image properly. This can be done using the im2uint8 function, which scales the input to a maximum value of 255, and converts it to uint8. Note that you'll have to remove the minimal value manually, if that is needed:
newImage = im2uint8(MHI{t} - min(MHI{t}(:)));
imwrite(newImage,'TMHI.jpg')
In case you really need to save the contents of the displayed figure in matlab (sometimes also useful when you use imagesc for display as it has some smart logic for properly scaling your value ranges) you might be interested in the savefig and saveas which lets you save the contents of a figure. Its also possible to save graphs or figures with subfigures like that.
In that case, you would use something like:
F = imshow(uint8(MHI{t}),[]);
saveas('MHI.png');
In case you really just need to save the image stored in MHI{t}, hbaderts 's answer is the way to go...
Just use my NormalizeImage function and save the image normaly:
img = NormalizeImage(imgDouble);
imwrite(img ,'MyImage.png');
My NormalizeImage function:
function img8bpp = NormalizeImage(imgDouble)
minImgDouble = min(imgDouble(:));
factor = (255-0)/(max(imgDouble(:)) - minImgDouble);
%img8bppB = im2uint8(imgDouble-minImgDouble);
img8bpp = uint8((imgDouble-minImgDouble).*factor);
%im2uint8 does not work, duno y
%imgDif = img8bppB - img8bpp;
end

Image processing Error in MATLAB

I was given a defined set of images (.png), I am supposed to detect each images Edges, then apply some image processing, but I have a problem.
First I an image array as follows :
imgArray = {'image_1.png','image_2.png','image_3.png'}
Then applied edging (sobel), using the MATLAB built in function edge so :
for i = 1:3
image=imread(imgArray{i});
image = edge(image,'sobel');
imgArray{i} = image;
end
based on that prvious code and my understanding, that the imageArray, now contains all 3 edged images.
Later on, I need to use the Edged images using that command image=imread(imgArray{i}); in a different place in the code, but it gives me an Error, I dont understand why does that happen ??
EDIT:
Here's the error I'm getting:
Error in ==> ImageCompare at 43 image=imread(imgArray{i});
imgArray = {'image_1.png','image_2.png','image_3.png'};
imgArrayEdged = strrep(imgArray, '.png', '_edged.png');
for i = 1 : length(imgArray)
image = imread(imgArray{i});
image = edge(image,'sobel');
imwrite(image, imgArrayEdged{i});
end
% later...
for i = 1 : length(imgArray)
if (your_condition)
image = imread(imgArray{i});
else
image = imread(imgArrayEdged{i});
end
end
Your imgArray contains file names as strings. In your loop, you are reading the image files and replacing each string in the cell array with image data.
If you absolutely require the file name strings later, you must create a second variable to hold the image data itself. If you only require the original images, just don't use imread later in the code!
Having read in an image file with imread once, there is no reason to waste time by reading the files again. It seems like you aren't quite aware of what state your data is in as it moves through your code. I suggest you use MATLAB's excellent debugger to step through and examine the type and content of the variables - you will quickly see where imread, which needs a file name, is inappropriate.