所以我正在尝试编写一个程序,它可以找出其中有多少特定颜色的像素。这些图像是用相机拍摄的照片,然后在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.");
}
}问题是我得不到我想要的结果。例如,当我必须获得1000个像素时,我或多或少地得到了,但我找不到我的错误所在。所以如果有人能告诉我我做错了什么。提前感谢大家的帮助。
发布于 2011-06-21 19:41:52
从你的代码中:
if ((green + 10 >= greent) && (green - 10 >= greent))如果是(a - 10 >= b),那么肯定是(a + 10 >= b)。看看你能不能理解为什么。
我想你的意思可能是
if ((green - 10 <= greent) && (greent <= green + 10))这样对条件进行排序有助于提高可读性,因为greent必须在green - 10和green + 10之间,并且在物理上也位于这两个表达式之间。
发布于 2011-06-21 19:41:15
试着使用这个循环:
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;
}
}
}其中,epsilon是每个通道的像素颜色和目标颜色之间的最大差异。
发布于 2011-06-21 19:42:53
我认为你的颜色对比不正确。您尝试将<=和>=混合在颜色周围的范围内。试试这个:
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;
}
}
}https://stackoverflow.com/questions/6424579
复制相似问题