Message Boards Message Boards

GROUPS:

[✓] Convert an rgb image into grayscale using For function and matrix?

Posted 6 months ago
584 Views
|
3 Replies
|
2 Total Likes
|

Hi, I'm new at image processing with mathematica and I need to convert a rgb image to a grayscale one using For function. I've tried this but I don't know how to do it:

enter image description here

3 Replies

Edward,

Why do you use For[] function. I strongly discourage you doing so. In Wolfram Language conversion from RGB to "Grayscale" is easier than pronouncing it :)

i  =  Import["ExampleData/coneflower.jpg"]; 
ImageColorSpace[i]
(* ==> "RGB" *)
iNew  =  ColorConvert[i,  "Grayscale"]; 
ImageColorSpace[iNew]
(* ==> "Grayscale" *)
Posted 6 months ago

I know I can do it in one step using Wolfram Language conversion but I was asked to do it with For function for a task

This is the easiest way I can think of right now:

rgbToGrayScale[imageIn_Image, factor_ : 1] :=
    Module[{res, w, h, i, j, r, g, b, data, image = imageIn},
       res = 
               If [StringMatchQ[ImageColorSpace[image], "RGB"] && ImageChannels[image] === 3,
                     If[(Interleaving /. Options[image, Interleaving]),
                          image = Image[image, Interleaving -> True];
                     ];

                     data = ImageData[image];

                     {w, h} = ImageDimensions[image];
                     res = ConstantArray[ConstantArray[0, w], h];

                     For[i = 1, i <= w, ++ i , 
                          For[j = 1, j <= h, ++ j,
                              {r, g, b} = data[[j, i]];
                                  res[[j, i]] = Mean[{r, g, b}^factor];
                          ];
                     ];

                     Image[res]
                     ,
                     image
               ];

       Return[res];
    ];

You can use it as follows:

rgbToGrayScale[i]
rgbToGrayScale[i, 2]
rgbToGrayScale[i, 1.34]

p.s. Algebra, Computer-Based Maths, 3D Printing have nothing to do with your question. Please consider removing them.

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract