How to convert a for loop script into a function
1 view (last 30 days)
Show older comments
Im=imread('Untitled23.png');
figure,imshow(Im);
title('Original Image');
%0.2989 * R + 0.5870 * G + 0.1140 * B
GIm=uint8(zeros(size(Im,1),size(Im,2)));
for i=1:size(Im,1)
for j=1:size(Im,2)
GIm(i,j)=0.2989*Im(i,j,1)+0.5870*Im(i,j,2)+0.1140*Im(i,j,3);
end
end
%Specifically im turning a regular image into grayscale, feel free to test my function :), but how do i convert it into a function.
0 Comments
Answers (1)
Image Analyst
on 14 Sep 2014
In ConvertToGrayscale.m, have this:
function grayImage = ConvertToGrayscale(filename)
grayImage = []; Initialize to null
if ~exist(filename, 'file')
message = sprintf('Image file not found:\n%s', filename);
uiwait(warndlg(message));
return;
end
originalImage = imread(filename);
[rows, columns, numberOfColorChannel] = size(originalImage);
if numberOfColorChannel > 1
grayImage = rgb2gray(originalImage);
else
grayImage = originalImage;
end
It could be made more robust (like using try/catch, checking for indexed images, etc.), but this is a good start. And I didn't test it, it's just off the top of my head, so you may have to do a little debugging (fix typos or whatever).
0 Comments
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!