Click here to Skip to main content
15,919,422 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to convert coloured image to grayscale in C or C++ ?
All the threads present here give solution in C#
Posted
Updated 20-Apr-20 16:56pm

:) :

0. Any color can be presented as a 3D vector with coordinates (r, g, b)
1. For any w/b color is valid (r == g == b)
2. Any vector has a length
3. Any converted w/b vector has the same length to the original
4. Any pixel of an image has a color

See also[^]
C++
void convert(CImage* pcImage)
{
  ASSERT(pcImage);

  int iWidth(pcImage->GetWidth());
  int iHeight(pcImage->GetHeight());
  
  if (iWidth && iHeight) {
    for (int i = 0; i < iWidth; i++) {
      for (int j = 0; j < iHeight; j++) {
        COLORREF clrOriginal(pcImage->GetPixel(i, j));
        float fR(GET_R(clrOriginal));
        float fG(GET_G(clrOriginal));
        float fB(GET_B(clrOriginal));

        float fWB = sqrt((fR * fR + fG * fG + fB * fB) /3);
        pcImage->SetPixel(i, j, RGB(fWB, fWB, fWB));
      }
    }
  }
}
 
Share this answer
 
v2
Comments
Amritanshu Pandia 9-Feb-12 7:29am    
can you provide a C or C++ code for converting coloured image to grayscale image
CPallini 9-Feb-12 8:06am    
I would do
fWB = sqrt(fR * fR + fG * fG + fB * fB)/3;
instead.
Eugen Podsypalnikov 9-Feb-12 8:10am    
Thank you,

but 3*(fWB * fWB) = (fR * fR + fG * fG + fB * fB) , isn't it ? :)
CPallini 9-Feb-12 8:15am    
Sorry, never mind. I need more caffein.
Espen Harlinn 9-Feb-12 8:38am    
5'ed!
 
Share this answer
 
Comments
Espen Harlinn 9-Feb-12 8:38am    
5'ed!
JackDingler 9-Feb-12 11:29am    
Note that every color element has a factor to determine how much input it should have in the final pixel value.

The following code though, begs for optimization. There is no need to use floating point math here.
byColor = ( GetRValue(cr) * 0.30 ) +
( GetGValue(cr) * 0.59 ) +
( GetBValue(cr) * 0.11 );

We can do this with all integers. We can multiply the factors by 1024, then do the math and shift by 10 to fake a divide by 1024...
byColor = (( (int) GetRValue(cr) * 307 ) +
( (int) GetGValue(cr) * 604 ) +
( (int) GetBValue(cr) * 113 )) >> 10;
The "exact" colour weightings are:
0.299083 0.585841 0.114076
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900