EDITION: Another question came up with a similar problem, but using
Java. So I essentially translated the code I created here (and even
I used the same example). If by chance some reader eventually
need a solution also in the Java language, please
refer this answer .
Well, since your image is not captured from the real world (a very important detail you did not put into the original question), it is much simpler to use a method like Location to get the job done automatically. Thresholding is a process in which you transform any image into a binary image (containing only two colors) by replacing all the pixels in the original image with one of the binary colors depending on their brightness be greater or smaller than a defined threshold.
As in your case the region of the tattoo is very different from the background, an average threshold value (% with%) is enough for an interesting result. But note that you may need to adjust it for a better effect on other images. The comparison is made with the brightness in the image, and the smaller the brightness the closer the color is to black (so the code only counts the pixels where the brightness is smaller than the threshold).
Here is a sample program:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Teste
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog file = new OpenFileDialog();
file.Filter = "jpg|*.jpg|png|*.png";
if (file.ShowDialog() == DialogResult.OK)
{
pictureBox1.ImageLocation = file.FileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
var limiar = 0.5;
var count = 0;
Bitmap img = new Bitmap(pictureBox1.Image);
for (var x = 0; x < img.Width; x++)
{
for (var y = 0; y < img.Height; y++)
{
Color pixelColor = img.GetPixel(x, y);
if (pixelColor.GetBrightness() < limiar)
{
count++;
img.SetPixel(x, y, Color.Red);
}
}
}
pictureBox1.Image = img;
var percent = ((float) count / (img.Width * img.Height)) * 100;
label1.Text = String.Format("A tattoo contém {0:d} pixels (ou seja, uma área equivalente a {1:f}%)", count, percent);
}
}
}
The home screen has the Picture Box, two buttons (one to load the image and display it and another to process it) and a label to display the result:
Afterprocessing,thecodenotonlycountsthepixels(andalsothepercentage,avaluemoreeffectivelyusefulbecauseitisnormalizedindependentlytothedimensionsoftheimage)butalsochangesthepixelsofthetattootoredtoeffectivelydemonstratewhatitwascalculated.Result:
Note: Note that processing uses the 0,5
class and not the Picture Box to access the raw pixels.