0

How do I detect white color in RGB color?

I mean how do I change the color in the code or what should I change in the code?

This code detect red color:

#include"math.h"
#include"conio.h"
#include"cv.h"
#include"highgui.h"
#include"stdio.h"
int main() {
    int i,j,k;
    int height,width,step,channels;
    int stepr, channelsr;
    int temp=0;
    uchar *data,*datar;
    i=j=k=0;
    IplImage *frame=cvLoadImage("red.jpg",1);
    IplImage *result=cvCreateImage( cvGetSize(frame), 8, 1 );
    if(frame==NULL ) {
        puts("unable to load the frame");exit(0);
    }
    printf("frame loaded");
    cvNamedWindow("original",CV_WINDOW_AUTOSIZE);
    cvNamedWindow("Result",CV_WINDOW_AUTOSIZE);
    height = frame->height;
    width = frame->width;
    step =frame->widthStep;
    channels = frame->nChannels;
    data = (uchar *)frame->imageData;
    stepr=result->widthStep;
    channelsr=result->nChannels;
    datar = (uchar *)result->imageData;
    for(i=0;i < (height);i++) for(j=0;j <(width);j++)
    if(((data[i*step+j*channels+2]) > (29+data[i*step+j*channels])) && 
            ((data[i*step+j*channels+2]) > (29+data[i*step+j*channels+1])))
        datar[i*stepr+j*channelsr]=255;
    else
        datar[i*stepr+j*channelsr]=0;
    cvShowImage("original",frame);
    cvShowImage("Result",result);
    cvSaveImage("result.jpg",result);
    cvWaitKey(0);
    cvDestroyWindow("original");
    cvDestroyWindow("Result");
    return 0;
}
Sam
  • 19,708
  • 4
  • 59
  • 82

1 Answers1

0

If you detect the 3 rgb channels to be nearly equal this will detect colours from black through grey to white. In order to check for white you could probably check each pixel for

1) being bright

r > 250 , g > 250, b > 250

2) colours are nearly equal abs(r - b) < 2, abs(g - b) < 2, abs(r - g) < 2 *

The values 250 and 2 were only an example you should experiment until you have a satisfying result.

You should change the conditional with code equivalent to the above

if(((data[i*step+j*channels+2]) > (29+data[i*step+j*channels])) && 
        ((data[i*step+j*channels+2]) > (29+data[i*step+j*channels+1])))
    datar[i*stepr+j*channelsr]=255;
else
    datar[i*stepr+j*channelsr]=0;

*NOTE; If the values r,g,b are unsigned (they are in this case) you should cast the numbers to signed like

abs((int)r - g) < 2

Dimitar Slavchev
  • 1,597
  • 3
  • 16
  • 20