How to read every next img in a file, then invert it, and save it?
You are now following this question
- You will see updates in your followed content feed.
- You may receive emails, depending on your communication preferences.
An Error Occurred
Unable to complete the action because of changes made to the page. Reload the page to see its updated state.
Show older comments
0 votes
So I need to invert/complement (change all the white to black and black to white) a bunch of images in a file. All of these images are named image10.jpg, image20.jpg, image30.jpg, etc. There could be up to a thousand of these images. I need to invert the colors of all these images and then re-save them. I would prefer to re-save them over their non-inverted image too. I know the command img1=~img1 inverts the image but I am just not quite sure how to do the rest.
Thanks in advance for any help.
Accepted Answer
Image Analyst
on 11 Feb 2013
0 votes
Are the images color, grayscale, or binary? Sometimes you'd say theImage = 255 - theImage. I don't know the format of this massive file that contains all your images. Is it a multi-page TIFF image? Or a dicom file? Saving your new image over your original images is a dangerous and risky thing to do unless you have a back up of them somewhere.
9 Comments
Matt
on 11 Feb 2013
It's just a bunch of jpg files in a folder. Saving them as something else would also work. Right now I have this code that works in inverting "image1"
I=imread('image1.jpg');
I=rgb2gray(I);
I=im2bw(I,graythresh(I));
I=~I;
imshow(I)
Image Analyst
on 11 Feb 2013
Edited: Image Analyst
on 11 Feb 2013
That doesn't invert them. It converts to grayscale, throwing away all color information, then binarizes the image according to the Otsu method. Is that what you want? And don't name your images I - it looks too much like 1 and l. An inversion would be
rgbImage = 255 - rgbImage;
Demo:
fontSize = 20;
format compact;
% Read in a standard MATLAB color demo image.
folder = fullfile(matlabroot, '\toolbox\images\imdemos');
baseFileName = 'peppers.png';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
if ~exist(fullFileName, 'file')
% Didn't find it there. Check the search path for it.
fullFileName = baseFileName; % No path this time.
if ~exist(fullFileName, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
rgbImage = imread(fullFileName);
% Get the dimensions of the image. numberOfColorBands should be = 3.
[rows columns numberOfColorBands] = size(rgbImage);
% Display the original color image.
subplot(2, 1, 1);
imshow(rgbImage);
title('Original Color Image', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
invertedImage = 255 - rgbImage;
subplot(2, 1, 2);
imshow(invertedImage);
title('Inverted Color Image', 'FontSize', fontSize);
Matt
on 11 Feb 2013
I just tried that command and yes that works too and it's easier. The reason my worked also is because all my images were already all black and white I just needed to invert the two colors.
Matt
on 11 Feb 2013
By my last comment i mean "rgbImage = 255 - rgbImage;" as your command. I'm looking at the Demo now.
Matt
on 11 Feb 2013
Does anyone else know what the code for this may be?
Image Analyst
on 11 Feb 2013
Code for what? I gave you to code to invert an image.
Matt
on 11 Feb 2013
Well I also need to know how to do everything that I said in my original post.
Image Analyst
on 11 Feb 2013
That's in the FAQ Walter referred you to. Can't you adapt that? Do you need us volunteers to do that for you?
Image Analyst
on 11 Feb 2013
All right. Here's your code:
%----------------------------------------------------------
% Program to read in all the RGB color images in a folder and
% invert them.
% Feb. 11, 2013, by Image Analyst
%----------------------------------------------------------
function RGB_Inversion_Demo()
% Change the current folder to the folder of this m-file.
if(~isdeployed)
cd(fileparts(which(mfilename)));
end
clc; % Clear command window.
close all; % Close all figure windows except those created by imtool.
workspace; % Make sure the workspace panel is showing.
fontSize = 16;
try
% Read in standard MATLAB color demo images.
% Construct the folder name where the demo images live.
imagesFolder = fullfile(matlabroot, '\toolbox\images\imdemos');
if ~exist(imagesFolder, 'dir')
% That folder didn't exist. Ask user to specify folder.
message = sprintf('Please browse to your image folder');
button = questdlg(message, 'Specify Folder', 'OK', 'Cancel', 'OK');
drawnow; % Refresh screen to get rid of dialog box remnants.
if strcmpi(button, 'Cancel')
return;
else
imagesFolder = uigetdir();
if imagesFolder == 0
% Exit if uer clicked Cancel.
return;
end
end
end
% Read the directory to get a list of images.
filePattern = [imagesFolder, '\*.jpg'];
jpegFiles = dir(filePattern);
filePattern = [imagesFolder, '\*.tif'];
tifFiles = dir(filePattern);
filePattern = [imagesFolder, '\*.png'];
pngFiles = dir(filePattern);
filePattern = [imagesFolder, '\*.bmp'];
bmpFiles = dir(filePattern);
% Add more extensions if you need to.
imageFiles = [jpegFiles; tifFiles; pngFiles; bmpFiles];
% Bail out if there aren't any images in that folder.
numberOfImagesProcessed = 0;
numberOfImagesToProcess = length(imageFiles);
if numberOfImagesToProcess <= 0
message = sprintf('I did not find any JPG, TIF, PNG, or BMP images in the folder\n%s\nClick OK to Exit.', imagesFolder);
uiwait(msgbox(message));
return;
end
% Create a figure for our images.
figure;
set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.
set(gcf,'name','Image Analysis Demo','numbertitle','off')
% Loop though all images.
numberOfImagesToProcess2 = 0;
for k = 1 : numberOfImagesToProcess
% Read in this one file.
baseFileName = imageFiles(k).name;
fullFileName = fullfile(imagesFolder, baseFileName);
originalImage = imread(fullFileName);
subplot(2, 1, 1);
imshow(originalImage, []);
[rows columns numberOfColorBands] = size(originalImage);
% Create a title for the image.
caption = sprintf('Original Color Image\n%s\n%d rows by %d columns by %d color channels', ...
baseFileName, rows, columns, numberOfColorBands);
% If there are underlines in the name, title() converts the next character to a subscript.
% To avoid this, replace underlines by spaces.
caption = strrep(caption, '_', ' ');
title(caption, 'FontSize', fontSize);
drawnow; % Force it to update, otherwise it waits until after the conversion to double.
numberOfImagesToProcess2 = numberOfImagesToProcess2 + 1;
% Invert the image.
invertedImage = 255 - originalImage;
subplot(2, 1, 2);
imshow(invertedImage, []);
title('Inverted Image', 'FontSize', fontSize);
% Overwrite original image (BAD PRACTICE).
% imwrite(invertedImage, fullFileName);
numberOfImagesProcessed = numberOfImagesProcessed + 1;
% Prompt user to continue, unless they're at the last image.
if k < numberOfImagesToProcess
promptMessage = sprintf('Currently displaying image #%d of a possible %d:\n%s\n\nDo you want to\nContinue processing, or\nCancel processing?',...
numberOfImagesProcessed, numberOfImagesToProcess, baseFileName);
button = questdlg(promptMessage, 'Continue?', 'Continue', 'Cancel', 'Continue');
if strcmp(button, 'Cancel')
break;
end
end
end
catch ME
errorMessage = sprintf('Error in function RGB_Hist_Demo.\n.\n\nError Message:\n%s', ME.message);
uiwait(warndlg(errorMessage));
end
More Answers (1)
Walter Roberson
on 11 Feb 2013
0 votes
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)