Einzelnen Beitrag anzeigen

Benutzerbild von jfheins
jfheins

Registriert seit: 10. Jun 2004
Ort: Garching (TUM)
4.579 Beiträge
 
#1

schnelle Bildverarbeitung?

  Alt 9. Sep 2010, 14:54
Hallo,
ich habe mal meine C# Kenntnisse ausgepackt und ein kleine Programm geschrieben. Das Teil soll mir Bilder auswerten, die ich für eine Studienarbeit mache.
Anforderung ist einfach: Anzahl schwarze Pixel zählen und zurückgeben. Mit GetPixel() ist das natürlich total lahm, deshalb war ich auf der Suche nach Alternativen und bin auf LockBits() gestoßen.

Aber genug der schönen Worte, hier mein Code:
Code:
private uint CountPixels(Image img)
        {
            var s = DateTime.Now;
            uint result = 0;
            int col = colorDialog1.Color.ToArgb();
            Bitmap bmp = new Bitmap(img);

            Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
            System.Drawing.Imaging.BitmapData bmpData =
                bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
                bmp.PixelFormat);

            bmpData.PixelFormat = System.Drawing.Imaging.PixelFormat.Format32bppArgb;


            // Get the address of the first line.
            IntPtr ptr = bmpData.Scan0;

            // Declare an array to hold the bytes of the bitmap.
            int pixelcount = bmp.Width * bmp.Height;
            int[] rgbValues = new int[pixelcount];

            // Copy the RGB values into the array.
            System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, pixelcount);

            for (int i = 0; i < rgbValues.Length; i++)
            {
                if (rgbValues[i] == col)
                    result++;
            }
            // Unlock the bits.
            bmp.UnlockBits(bmpData);
            bmpData = null;
            bmp.Dispose();
            rgbValues = null;

            var e = DateTime.Now;
            System.Console.WriteLine((e - s).TotalMilliseconds);

            return result;
        }
Braucht bei mir für ein 10 MP Bild ungefähr 500ms. Geht das noch schneller?
Danke schonmal im Voraus

P.S.: Wenn möglich bitte ohne unsafe Code.


P.P.S.: Hier der Aufruf der Funktion:
Code:
// For Schleife
            try
            {
                Image img = Image.FromFile(Files[i].FullName);
                try
                {
                    var x = CountPixels(img);
                    // Anzeige von x                  
                }
                finally
                {
                    img.Dispose();
                }
            }
            catch (OutOfMemoryException)
            {
            }

Geändert von jfheins ( 9. Sep 2010 um 15:26 Uhr)
  Mit Zitat antworten Zitat