2009-10-19 143 views
1

如何识别C#中的黑/黑图像。是否有任何API来检查图像可见度或暗度比率?在我的应用程序中,当复制图像时,我想检查每个图像并且想要放弃黑色图像。如何识别C#中的黑色或黑色图像?

任何想法如何实现这一目标?

+0

@dreamwalker你不需要去走一走加入。 net标签到每一个C#问题。这不会增加网站的价值。 – Servy 2013-09-17 19:27:07

回答

5

一个主意,让图像暗度/亮度可以:

Bitmap bitmap = // the bitmap 
var colors = new List<Color>(); 
for (int x = 0; x < bitmap.Size.Width; x++) 
{ 
    for (int y = 0; y < bitmap.Size.Height; y++) 
    { 
     colors.Add(bitmap.GetPixel(x, y)); 
    } 
} 

float imageBrightness = colors.Average(color => color.GetBrightness()); 

也许考虑深色图像为那些与亮度低于0.1(或有关的任何其他数值)

+5

Bitmap.GetPixel超慢。 DreamWalker使用BitMap.LockBits和不安全代码的解决方案将远远超过这一点... – ParmesanCodice 2009-10-19 09:37:21

+0

正如ParmesanCodice提到的,我现在过滤稍大的图像(640x480),而深色图像过滤器使其非常缓慢。 – zHs 2010-07-27 12:59:53

0

我想通过启动遍历图像中的所有像素,计算每个像素的颜色,然后平均'V'分量(代表颜色的'亮度')。

7
// For fast access to pixels   
public static unsafe byte[] BitmapToByteArray(Bitmap bitmap) { 
    BitmapData bmd = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, 
            PixelFormat.Format32bppArgb); 
    byte[] bytes = new byte[bmd.Height * bmd.Stride]; 
    byte* pnt = (byte*) bmd.Scan0; 
    Marshal.Copy((IntPtr) pnt, bytes, 0, bmd.Height * bmd.Stride); 
    bitmap.UnlockBits(bmd); 
    return bytes; 
} 

public bool IsDark(Bitmap bitmap, byte tolerance, double darkProcent) { 
    byte[] bytes = BitmapToByteArray(bitmap); 
    int count = 0, all = bitmap.Width * bitmap.Height; 
    for (int i = 0; i < bytes.Length; i += 4) { 
     byte r = bytes[i + 2], g = bytes[i + 1], b = bytes[i]; 
     byte brightness = (byte) Math.Round((0.299 * r + 0.5876 * g + 0.114 * b)); 
     if (brightness <= tolerance) 
      count++; 
    } 
    return (1d * count/all) <= darkProcent; 
} 

public void Run(Bitmap bitmap) { // Example of use 
    // some code 
    bool dark = IsDark(bitmap, 40, 0.9); 
    // some code 
} 
+1

+1,它可以帮助一些用户在亮度线上提供一些数学解释。 – user7116 2009-11-03 22:04:03

3

可以使用AForge.NJET框架,其中包括图像处理的支持。 例如,请参阅ImageStatisticsHSL Class。选择一个合适的Saturation值,或使用Luminance直方图。

该类用于累积图像的统计值,如直方图,平均值,标准偏差等,用于每个HSL颜色通道。

该类接受24和32 bpp彩色图像进行处理。

样品使用C#:

// gather statistics 
ImageStatisticsHSL stat = new ImageStatisticsHSL(image); 
// get saturation channel's histogram 
ContinuousHistogram saturation = stat.Saturation; 
// check mean value of saturation channel 
if (saturation.Mean > 0.5) 
{ 
    // do further processing 
} 
0

感谢以利沙的想法,我做它通过这种方式:

Bitmap bitmap = new Bitmap("123712.jpg"); 
float brightness = 0; 
for (int x = 0; x < bitmap.Size.Width; x++) 
{ 
    for (int y = 0; y < bitmap.Size.Height; y++) 
    { 
      brightness += bitmap.GetPixel(x, y).GetBrightness(); 
    } 
} 

float average = brightness/(bitmap.Size.Width * bitmap.Size.Height); 
+1

euhm,那最后一行是错误的?应该是bitmap.Size.Width * bitmap.Size.Height – Stormenet 2009-10-19 11:00:13

+0

是啊,我错了!我没有意识到这一点。这就是为什么我在考虑为什么平均数太大。感谢您更正:) – zHs 2009-10-19 15:02:18