Click here to Skip to main content
15,890,282 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a function which should change the colors in an image to their opposites. Red to green, green to blue, and blue to red. I have thinking and trying for a while now, but I can not get it to work. However, I know that there is not any problem with my code. Because the image does change colors, but I have a hard time to make it right.

What I have tried:

This is the code I have for now. I tried to look at a color wheel to see if I was able to move the pixel's color a third of the wheel. Color Wheel Chart Online[^]

My code looks like this:
C++
void reColor(Image *img) {

	img->height = 200;
	img->width = 150;

	for (unsigned int i = 0; i < img->height; i++)
	{
		for (unsigned int j = 0; j < img->width; j++)
		{
			if ((img->pixels[i][j].r <= 255 && img->pixels[i][j].g <= 255)                        && img->pixels[i][j].b == 0){
				while (img->pixels[i][j].r != 0) {
					img->pixels[i][j].r -= 1;
					img->pixels[i][j].g += 1;
				}
			}
			else if ((img->pixels[i][j].r == 0 && img->pixels[i][j].g 
<= 255) && img->pixels[i][j].b <= 255) {
				while (img->pixels[i][j].g != 0) {
					img->pixels[i][j].g -= 1;
					img->pixels[i][j].b += 1;
				}
			}
			else if ((img->pixels[i][j].r <= 255 && img->pixels[i][j].g == 0) && img->pixels[i][j].b <= 255) {
				while (img->pixels[i][j].b != 0) {
					img->pixels[i][j].b -= 1;
					img->pixels[i][j].r += 1;
				}
			}
		}
	}
}
Posted
Updated 5-Jan-17 15:39pm

They seemed contradictory:
Quote:
change RGB colors to their opposites
Quote:
look at a color wheel to see if I was able to move the pixel's color a third of the wheel

It the title is correct, then isn't it just a matter of:
newR = 255 - oldR
newG = 255 - oldG
newB = 255 - oldB

regardless of the programming language.
 
Share this answer
 
v2
A quick search of CodeProject in less than 30 seconds served up this gem: Fundamentals of Image Processing - behind the scenes[^]
 
Share this answer
 
If you want the inverted color which affects both hue and lightness, a simple invert will do.

Just convert from hex to RGB and invert each channel,

R = R *-1 + 255
G = G *-1 + 255
B = B *-1 + 255


And then convert back to hex.

If you want the opposite hue, without affecting lightness, the most straightforward way is to convert from hex to HSL and rotate the hue 180 degrees.

Convert from hex to HSL and rotate H 180 degrees.

H = H +180 % 360

And then convert back to hex.

Taken from here[^] .
 
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