Make skin color black & others white

private  Bitmap skin_color_segmentation(Bitmap bm)
{
Bitmap bmp = new Bitmap(bm.Width, bm.Height);

double tot_pixel = bm.Height * bm.Width;
tot_pixel /= 100;
tot_pixel *= 10;
int min_x = bm.Width + 5;
int max_x = 0;
int max_y = 0;
int min_y = bm.Height + 5;

Color color = new Color();
double g, r, avg = 0;
double f_upper, f_lower, w, l;
bool R1, R2, R3, R4, s;
double c, cr, cb;
R1 = R3 = R4 = s = false;
R2 = true;

int cr_start = 140;
int cr_end = 170;
int cb_start = 105;
int cb_end = 150;

for (int i = 0; i < bm.Width; i++)
{
for (int j = 0; j < bm.Height; j++)
{
color = bm.GetPixel(i, j);
r = Convert.ToDouble(color.R) / Convert.ToDouble(color.R + color.G + color.B);
g = Convert.ToDouble(color.G) / Convert.ToDouble(color.R + color.G + color.B);

f_upper = -1.3767 * r * r + 1.0743 * r + 0.1452;
f_lower = -0.776 * r * r + 0.5601 * r + 0.1766;

if (g > f_lower && g < f_upper)
R1 = true;
else
R1 = false;

w = Math.Pow((r – 0.33), 2) + Math.Pow((g – 0.33), 2);

if (w <= 0.0004)
{
R2 = true;
avg++;
}
else
R2 = false;

if (color.R > color.G && color.G > color.B)
R3 = true;
else
R3 = false;

if ((color.R – color.G) >= 45)
R4 = true;
else
R4 = false;

if (R3 && R4)
s = true;
else
s = false;

c = 0.257 * Convert.ToDouble(color.R) + 0.504 * color.G + 0.098 * color.B + 16;
cb = 0.148 * Convert.ToDouble(color.R) – 0.291 * Convert.ToDouble(color.G) + 0.439 * Convert.ToDouble(color.B) + 128;
cr = 0.439 * Convert.ToDouble(color.R) – 0.368 * Convert.ToDouble(color.G) – 0.071 * Convert.ToDouble(color.B) + 128;

if (s)
{
bmp.SetPixel(i, j, Color.Black);
R1 = R3 = R4 = s = false;
R2 = true;

if (i < bm.Width / 2 && i < min_x)
{
min_x = i;
}
if ((i >= bm.Width / 2 && i < bm.Width) && i > max_x)
{
max_x = i;
}

if (j < bm.Height / 2 && j < min_y)
{
min_y = j;
}
if ((j >= bm.Height / 2 && i < bm.Height) && j > max_y)
{
max_y = j;
}
}
else
bmp.SetPixel(i, j, Color.White);
}
}
return bmp;
}

Advertisements