Myyuanlaipic = Imread (' e:/image/matlab/darkmouse.jpg ');% read images in RGB format
Myfirstgraypic = Rgb2gray (myyuanlaipic);% conversion of RGB to grayscale images with existing functions
[Rows, cols, colors] = size (myyuanlaipic),% gets the parameters of the matrix of the original image
Midgraypic = zeros (rows, cols);% uses the resulting parameters to create a full-zero matrix, which is used to store grayscale images produced by the following methods
Midgraypic = Uint8 (midgraypic);% converts the entire 0 matrix created into uint8 format, since the image is double when created with the above statement
For i = 1:rows
for j = 1:cols
sum = 0;
For k = 1:colors
sum = sum + myyuanlaipic (i, J, K)/3;% key formula for conversion, sum is not more than 255 each time because of the number behind
End
Midgraypic (i, j) = sum;
End
End
Imwrite (midgraypic, ' e:/image/matlab/darkmousegray.png ', ' png ');
% display the original RGB image
Figure (1);
Imshow (Myyuanlaipic);
% shows grayscale images that have been calculated by the system function
Figure (2);
Imshow (Myfirstgraypic);
% display grayscale images after conversion
Figure (3);
Imshow (Midgraypic);
Of course, you can also use RGB to YUV image, so you can get the y image, in order to obtain a grayscale image