how to code the following program in MATLAB 2010

open 24-bit color image in read mode
store image height to m and width to n, respectively
declare two 2-D Matrices, matrix[m][n], matrix1[m][n]
read pixel one by one until end of file
{
matrix1[i][j] = bi.getRGB(i,j)
b1[i][j]= (bi.getRGB(i,j)) & 0x000000FF
g1[i][j]= (bi.getRGB(i,j) & 0x0000FF00) >> 8
r1[i][j]= (bi.getRGB(i,j) & 0x00FF0000) >> 16
int avg = (r1[i][j]+g1[i][j]+b1[i][j])/3
int newRGB = 0xFF000000 + (avg << 16) + (avg << 8 ) + avg
matrix[i][j] = newRGB
}
write matrix[m][n] to another image file
close all the files

 Accepted Answer

Ritu - is the above code just creating a grayscale image since it seems that each red, green and blue pixel becomes the average of the three?
Try the following to read an RGB image note that when you read a colour image (from file) the third dimension of the matrix will be used to get the pixel colour (red, green blue) data.
% read the image from file
clrImg = imread('someImageFileName.jpg');
% get the dimensions of the image
[m,n,c] = size(clrImg);
if c==3
% create the new image
gsImg = cast(zeros(m,n,c),class(clrImg));
% average each pixel
for u=1:m
for v=1:n
% get the red, green and blue channel data
r = clrImg(u,v,1);
g = clrImg(u,v,2);
b = clrImg(u,v,3);
% average the three and populate the gray scale image
gsImg(u,v,:) = r/3 + g/3 + b/3;
end
end
% write to file
imwrite(gsImg,'myNewImageFile.jpg');
end
Note that the above divides each r, g, and b value by three and then sums them to get the average. I do this instead of
(r + b + g)/3
to handle the case where the data type for the clrImg is unsigned integer and so adding the three would result in the sum being clipped at the maximum value for that data type. (For example if the data type is 8-bit unsigned integer and all three are 255, then summing the three would result in 255 and not the expected 765. You can do as above, or use doubles instead and then cast the gsImg back to the type of the original image.
Note also the difference in how we access the matrix elements - we use open brackets rather than the square ones.
Try the above and see what happens!

1 Comment

Thnx Sir, its working, really gd work. Thanxxxx once again.

Sign in to comment.

More Answers (0)

Categories

Find more on Convert Image Type in Help Center and File Exchange

Asked:

on 19 Apr 2015

Commented:

on 20 Apr 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!