i am trying to convert a rgb image to a grayscale one this is the code i am using to generate random pixels for the existing image ... i am using a .h file to generate the output file too ... This is the image.h file : https://www65.zippyshare.com/v/yWLb2IjG/file.html and this is a the used sample : https://www65.zippyshare.com/v/Cx5U4cua/file.html
#include<iostream>
#include<stdlib.h>
#include<time.h>
#include<iomanip>
#include"image.h"
using namespace std;
int main(){
Image im=readPPM("./xmas.ppm");
int largeur=im.w, hauteur=im.h;
cout<<"Ouverture d'une image de largeur "<<largeur<<" et de hauteur "<<hauteur<<endl;
srand(time(NULL));
for(int j=0;j<largeur;j++){
for (int i=0;i<hauteur;i++){
im(j,i).r +=(rand()%100)/300.0;
im(j,i).g +=(rand()%100)/300.0;
im(j,i).b +=(rand()%100)/300.0;
}
}
savePPM(im,"./out.ppm");
return 0;
}
for the grayscale i have tried to add : im(j,i) +=0.2126*im(j,i).r+0.7152*im(j,i).g+0.0722*im(j,i).b;
but it does not work i tried it also with 33% for each color and 0.3 for red 0.57 for green and 0.11 for blue and same result . it does not work
There is a very simple fix, but I'm going to explain what's going on first.
for the grayscale i have tried to add :
im(j,i) +=0.2126*im(j,i).r+0.7152*im(j,i).g+0.0722*im(j,i).b;
Let's look at why this "doesn't work"...
So, Image::operator(int,int)
returns a Rgb&
. At least we know we're dealing with a reference so we should be able to modify the value.
Now, you are invoking Rgb::operator+=(float)
which doesn't exist. But this won't be a compiler error because of Rgb& operator += (const Rgb &rgb)
, and there is an implicit constructor Rgb(float)
. So what is that doing? Let's break it down:
0.2126*im(j,i).r+0.7152*im(j,i).g+0.0722*im(j,i).b
+=
operator implicitly constructs a grayscale Rgb value from that, and adds it to the existing image value. The above description looks like this in code:
float lum = 0.2126f * im(j,i).r + 0.7152f * im(j,i).g + 0.0722f * im(j,i).b;
img(j,i) += Rgb(lum);
By adding it, you are taking the existing color value and offsetting each channel by the same amount. This results in a new color that is much brighter.
Instead, you want to change the value to be the new one you just calculated:
img(j,i) = Rgb(lum);
I hope you can see the difference.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.