Skip to content

Instantly share code, notes, and snippets.

@mganss
Last active July 15, 2019 08:14
Show Gist options
  • Save mganss/6826378 to your computer and use it in GitHub Desktop.
Save mganss/6826378 to your computer and use it in GitHub Desktop.
Simple human skin color detection

C# port of a simple skin color detection algorithm. Python original by SpliFF here. See also this Stack Overflow question.

Produces a lot of false positives but is great for quickly filtering a large set of unknown images.

using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
namespace SkinScanner
{
class Program
{
static void Main(string[] args)
{
foreach (var dir in args)
{
foreach (var file in Directory.GetFiles(dir))
{
try
{
using (var img = Image.FromFile(file) as Bitmap)
{
if (img != null)
{
if (HasSkin(img))
Console.Out.WriteLine(file);
}
// else not an image
}
}
catch
{
// error reading file
}
}
}
}
const int MinSkinPercentage = 25;
static bool HasSkin(Bitmap img)
{
int total = 0, skin = 0;
var startx = 0;
var endx = img.Width;
var starty = 0;
var endy = img.Height;
//var startx = (int)(0.2 * img.Width);
//var endx = (int)(0.8 * img.Width);
//var starty = (int)(0.2 * img.Height);
//var endy = (int)(0.8 * img.Height);
for (int y = starty; y < endy; y++)
{
for (int x = startx; x < endx; x++)
{
var p = img.GetPixel(x, y);
var s = IsSkin(p);
if (s) skin++;
total++;
}
}
return ((double)skin / total) > (MinSkinPercentage / 100.0);
}
static bool IsSkin(Color p)
{
return p.R > 60 && (p.G < p.R * 0.85) && (p.B < p.R * 0.7) && (p.G > p.R * 0.4) && (p.B > p.R * 0.2);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment