Message Boards Message Boards

0
|
5505 Views
|
3 Replies
|
2 Total Likes
View groups...
Share
Share this post:

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

Posted 6 years ago

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

POSTED BY: Edward Johnson
3 Replies

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.

POSTED BY: Mikayel Egibyan
Posted 6 years 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

POSTED BY: Edward Johnson

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 BY: Mikayel Egibyan
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