使用C#将图像转换为灰度

时间:2014-02-20 16:46:19

标签: c# opencv

大家好我想在我的目录中将所有图像转换为灰度,但我知道的代码只能逐一执行该任务!!但我有很多图像我想要如果有一个代码可以转换所有图像目录到灰度或

1 个答案:

答案 0 :(得分:1)

假设您有一个名为path的变量,它是要处理图像的文件夹的路径,并假设您可以使用WPF API转换图像:

DirectoryInfo dirInfo = new DirectoryInfo(path);

foreach ( FileInfo fileInfo in dirInfo.EnumerateFile() ) {
    ProcessImage(FileInfo.FullName);
}

void ProcessImage( string image ) {
    byte[] imageData = null;

    try {
        // Load the data in the file into a  byte array for processing.
        imageData = File.ReadAllBytes( image );

    } catch ( Exception) {
        // Your error handling code here
    }

    // We're going to put the image into this object
    BitmapImage src = new BitmapImage();

    try {
        // Load the image into a memory stream, then into src.
        using( MemoryStream stream = new MemoryStream( imageData ) ) {
            src.BeginInit();
            src.CacheOption = BitmapCacheOption.OnLoad; // Causes the bitmap data to be loaded now, not at a later time.
            src.StreamSource = stream;
            src.EndInit();
        }
    } catch ( NotSupportedException ) {
        // The bitmap format is not supported.  Your error handler here.
    }

    try {
        // Create a FormatConvertedBitmap object & set it up.
        FormatConvertedBitmap dst = new FormatConvertedBitmap();
        dst.BeginInit();
        dst.DestinationFormat = PixelFormats.Gray8;  // Use whatever gray scale format you need here
        dst.Source            = src;

        // Now convert the image to 8 bits per pixel grey scale.
        dst.EndInit();

        // Compute the dst Bitmap's stride (the length of one row of pixels in bytes).
        int stride = ( ( dst.PixelWidth * dst.Format.BitsPerPixel + 31 ) / 32 ) * 4;

        // Allocate space for the imageBytes array.
        imageBytes = new byte[ stride * dst.PixelHeight ];

        // Get the pixels out of the dst image and put them into imageBytes.
        dst.CopyPixels( Int32Rect.Empty, imageBytes, stride, 0 );

    } catch ( Exception ex ) {
        // Your error handler here.
    }

    // Any other code to save or do something else with the image.
}