EDIT: Another question came up with a similar problem, but using
Java. So I essentially translated the code I created here (and even
used the same example). If by chance any reader eventually
need a solution also in the Java language, please
reference this answer.
Well, since your image is not captured from the real world (a very important detail that you didn’t put in the original question), it’s much simpler to use a method like the limiarization to do the job automatically. The limiarization (thresholding in English) is a process in which you transform any image into a binary image (containing only two colors) replacing all pixels in the original image with one of the binary colors depending on their brightness being greater or less than a defined threshold.
As in your case the tattoo region is very distinct from the background, an average threshold value (0,5
) 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 lower the brightness the closer the color is to black (so the code only counts the pixels in which the brightness is minor than the threshold).
Here is an example 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 one to process it) and a label to display the result:
After processing, the code not only counts the pixels (and also the percentage, a value that is more effective because it is normalized independently to the dimensions of the image) but also changes the pixels of the tattoo to red to effectively demonstrate what has been calculated. Upshot:
Note: The processing uses the class Bitmap
not the Picture Box to access the raw pixels.
Guys, thank you very much, here are more details: I would need to press a button that would count how many pixels there are in the drawing, that is without the background, it is not necessary to define the color, just without counting the background. Request more details as needed. Obg
– Emanuel Borges