Introduction
Sometimes when we work with images, specially in JPG format, we observe that there are many pixels that are close to each other
by their RGB color like RGB(255,255,255) and RGB(255,254,250). When we open these images in Paint, and want to color one area, these pixels will be separate and don't color. Often it's a problem. To fix it, we have to convert these pixels to base color (color of assigned area).
Background
To get information about this subject, you can read or search about Detect edge in image processing.
Algorithm
At first, to detect these pixels, we need to have a Base Color to compare pixels with this for detecting close pixels by color
around an edge. Put and choose a pixel as base color and get its RGB, call those r1, g1, b1.
In a cycle, we gauge all pixels of image. Get those RGB in r2, g2, b2 names and calculate conditions to detect. Everywhere that
|r2-r1| is less than tolerance and |g2-g1| is less than tolerance and|b2-b1| is less than tolerance, this is a pixel that is close to base color and
then put it as base color. We repeat this algorithm until the end of images. The final image is an image that doesn't have any pixel that
will be close to backcolor by RGB and all pixels of the base area are the same and equal.
Simulation of Algorithm in Code
CString s;long r,g,b;USES_CONVERSION;char *ar=0;unsigned char tol;
rtol.GetWindowText(s);ar=T2A(s.GetBuffer());tol=atoi(ar);
rt.GetWindowText(s);ar=T2A(s.GetBuffer());r=atoi(ar);
gt.GetWindowText(s);ar=T2A(s.GetBuffer());g=atoi(ar);
bt.GetWindowText(s);ar=T2A(s.GetBuffer());b=atoi(ar);
for(register unsigned short int x=0 ; x < i.GetWidth();
x++)for(register unsigned short int y=0 ; y < i.GetHeight(); y++){
long r1,g1,b1;
COLORREF clr=i.GetPixel(x,y);
r1=GetRValue(clr);g1=GetGValue(clr);b1=GetBValue(clr);
if(abs(r1-r)<=tol&&abs(g1-g)<=tol&&abs(b1-b)<=tol){ i.SetPixel(x,y,RGB(0,0,255));
}
}
Application
For example, imagine that want draw an image in transparent mode. To do this, we need a color to transparent pixels that have this
color. You know in programming if other pixels are different even 1 unit of R or G or B in RGB Color, this pixel will not choose as transparent
color. In fact, this algorithm and program is used in applications.
I hope it will be useful for you. Thanks in advance.
History
- 9th May, 2013: Initial version