我是c#中使用图像的新手。
我这样做了:
private bool IsBitonal(string FilePath)
{
Bitmap bitmap = new Bitmap(FilePath);
return (bitmap.PixelFormat == PixelFormat.Format1bppIndexed)
}
这是工作与。png文件,但不与。jpeg文件工作,谁能帮助我?
是否有任何解决方案来找到图像是对位的?
我使用加载图形的东西,它也不工作与我。
private bool IsBitonal(string filePath)
{
bool isBitonal = false;
try
{
Bitmap bitmap = new Bitmap(filePath);
Graphics graphics = Graphics.FromImage(bitmap);
}
catch (Exception ex)
{
isBitonal = true;
}
return isBitonal;
}
Yeah I got Solution From Tomaz Answer
这是我在c#中的答案:
public bool IsBitonal(Bitmap YourCurrentBitmap)
{
Color c;
long Eadges = 0;
long Others = 0;
for (int i = 0; i < YourCurrentBitmap.Width; i++)
{
for (int j = 0; j < YourCurrentBitmap.Height; j++)
{
c = YourCurrentBitmap.GetPixel(i, j);
if (!(c.R == c.G && c.G == c.B)) return false;
if (c.R <= 16||c.R >= 255-16)
Eadges++;
else
Others++;
}
}
double proportion = Eadges / (double)Others;
// here is estimation based on you requirement you can change
return proportion > 10;;
}
JPEG图像按照定义是用颜色定义的。由于压缩伪影,即使是保存在JPEG中并重新读取的双色图像也永远不会是双色的。
你所能做的就是做一些估计,例如创建一个直方图,并手动检查(有一些错误)值是否沿着它的边缘分布。
编辑:这应该是一种计算直方图的快速方法。如果您喜欢(更)慢,但更简单的方法,您可以使用getPixel()来代替图片中的每个像素。
基于:http://aforge.googlecode.com/svn/tags/AForge-1.5.0/Sources/Imaging/ImageStatisticsHSL.cs
private int[] getHistogram( BitmapData imageData )
{
int width = imageData.Width;
int height = imageData.Height;
int offset = imageData.Stride - width * 3;
int[] l = new int[256];
unsafe
{
byte * p = (byte *) imageData.Scan0.ToPointer( );
// for each line
for ( int y = 0; y < height; y++ )
{
// for each pixel
for ( int x = 0; x < width; x++, p += 3 )
{
int bright = p[RGB.R] + p[RGB.G] + p[RGB.B];
bright /= 3;
l[bright]++;
}
p += offset;
}
}
return l;
}
我现在不能测试它,但你应该很容易理解这个想法。你可以使用像AForge这样的库。NJET生成直方图。
一旦你有了直方图,你应该检查是否所有的值都位于两个点附近。
int[] hist = getHistogram(imageData);
hist[n]
是亮度为'n'的像素个数(范围从0到255)
对于理想图像,所有像素要么是白色要么是黑色,因此hist[0]和hist[255]将被设置,所有其他值将为零。相反,所有值将分布在0和255附近。例如,你可以计算黑白像素与其他像素的比例。
int eadges = 0; // black, white or very close to black/white
int others = 0;
for(int i =0; i<hist.length; i++)
{
if(i < 16 || i > 255-16) eadges += hist[i];
else others += hist[i];
}
double proportion = eadges/(double)others;
return proportion > 10;
16和10只是示例-您可以选择其他数字以获得不同的检测精度。
如果你愿意,你应该能够很容易地找到更多关于直方图和其他计算方法的信息。先看一下Google图片的直方图。
与PNG图像相反,由于其编码颜色信息的方式,JPEG图像不能是双色调的。您可以在这里阅读更多内容:http://en.wikipedia.org/wiki/JPEG
我猜你可以数一下图片中不同颜色的数量,看看它是否是双色调的,但是JPEG伪影(即边缘周围的颜色流血)会给出不正确的结果。
简单的方法:尝试将图像转换为PNG,然后运行代码。
编辑:加载为图形应该做的伎俩,不是吗?