Beispiel #1
0
        private byte FindAverageThreshold(int min, int max)
        {
            int threshold = 0, count = 0;

            unsafe
            {
                BitmapData bitmapData = ProcessedBitmap.LockBits(new Rectangle(0, 0, ProcessedBitmap.Width, ProcessedBitmap.Height), ImageLockMode.ReadWrite, ProcessedBitmap.PixelFormat);

                int   bytesPerPixel  = Image.GetPixelFormatSize(ProcessedBitmap.PixelFormat) / 8;
                int   heightInPixels = bitmapData.Height;
                int   widthInBytes   = bitmapData.Width * bytesPerPixel;
                byte *ptrFirstPixel  = (byte *)bitmapData.Scan0;

                Parallel.For(0, heightInPixels, y =>
                {
                    byte *currentLine = ptrFirstPixel + (y * bitmapData.Stride);
                    for (int x = 0; x < widthInBytes; x = x + bytesPerPixel)
                    {
                        int blue      = currentLine[x];
                        int green     = currentLine[x + 1];
                        int red       = currentLine[x + 2];
                        var intensity = (byte)(0.3 * red + 0.6 * green + 0.1 * blue);
                        if ((intensity >= min) && (intensity <= max))
                        {
                            threshold += intensity;
                            count++;
                        }
                    }
                });
                ProcessedBitmap.UnlockBits(bitmapData);
            }

            return((byte)(threshold / count).TruncateRgb());
        }
        public void SetUpColors()
        {
            unsafe
            {
                BitmapData bitmapData = ProcessedBitmap.LockBits(new Rectangle(0, 0, ProcessedBitmap.Width, ProcessedBitmap.Height), ImageLockMode.ReadWrite, ProcessedBitmap.PixelFormat);

                int   bytesPerPixel  = Image.GetPixelFormatSize(ProcessedBitmap.PixelFormat) / 8;
                int   heightInPixels = bitmapData.Height;
                int   widthInBytes   = bitmapData.Width * bytesPerPixel;
                byte *ptrFirstPixel  = (byte *)bitmapData.Scan0;

                for (int y = 0; y < heightInPixels; y++)
                {
                    byte *currentLine = ptrFirstPixel + (y * bitmapData.Stride);
                    for (int x = 0; x < widthInBytes; x = x + bytesPerPixel)
                    {
                        int b = currentLine[x];
                        int g = currentLine[x + 1];
                        int r = currentLine[x + 2];

                        var color = Color.FromArgb(r, g, b);
                        if (!_colorList.Contains(color))
                        {
                        }
                        _colorList.Add(color);
                    }
                }
                ProcessedBitmap.UnlockBits(bitmapData);
            }
        }