所以我正在尝试制作一个程序,可以找到它中有多少像素的特定颜色.图像是用相机拍摄的照片,之后在photoshop上标记了一些区域,我需要找到这些像素的确切数量.但我几乎没有问题.我正在使用getPixel(x,y),但我正在与我想要的Color.FromArgb(红色,绿色,蓝色)进行比较但是......我的第一个问题是颜色有点不同,例如我想要找出RGB 116,110,40的颜色但是当你在photoshop上用这种颜色绘制时,一些像素会得到一些不同的颜色,比如RGB 115,108,38(以及其他相似的颜色),我也想包括它.所以我终于提出了这个代码(但似乎id现在正常工作):
public Form1()
{
InitializeComponent();
}
Bitmap image1;
int count=0;
int red, green, blue;
int redt, greent, bluet;
double reshenie;
private void button1_Click(object sender, EventArgs e)
{
try
{
red = int.Parse(textBox1.Text);
green = int.Parse(textBox2.Text);
blue = int.Parse(textBox3.Text);
// Retrieve the image.
image1 = new Bitmap(@"C:\bg-img.jpg", true);
double widht, height, pixel ;
int x, y;
MessageBox.Show(pixel.ToString());
// Loop through the images pixels
for (x = 0; x < image1.Width; x++)
{
for (y = 0; y < image1.Height; y++)
{
Color pixelColor = image1.GetPixel(x, y);
redt = pixelColor.R;
greent = pixelColor.G;
bluet = pixelColor.B;
if ((red+10>=redt) && (red-10>=redt))//i used +-10 in attempt to resolve the problem that i have writed about the close colours
{
if ((green + 10 >= greent) && (green - 10 >= greent))
{
if ((blue + 10 >= bluet) && (blue - 10 >= bluet))
{
count += 1;
}
}
}
}
}
pictureBox1.Image = image1;
MessageBox.Show("Imashe " + count.ToString());
count = 0;
}
catch (ArgumentException)
{
MessageBox.Show("There was an error." +
"Check the path to the image file.");
}
}
Run Code Online (Sandbox Code Playgroud)
问题是我没有得到我期望的结果.例如,当我必须得到像1000像素我或多或少,我无法找到我的错误.所以如果有人能让我知道我做错了什么.在此先感谢您的所有帮助.
请尝试使用此循环:
int epsilon = 10;
for (x = 0; x < image1.Width; ++x)
{
for (y = 0; y < image1.Height; ++y)
{
Color pixelColor = image1.GetPixel(x, y);
redt = pixelColor.R;
greent = pixelColor.G;
bluet = pixelColor.B;
if (Math.Abs(redt - red) <= epsilon &&
Math.Abs(greent - green) <= epsilon &&
Math.Abs(bluet - blue) <= epsilon)
{
++ count;
}
}
}
Run Code Online (Sandbox Code Playgroud)
epsilon每个通道的像素颜色和目标颜色之间的最大差异在哪里.