加速位图灰度转换,OpenMP是C#中的一个选项吗?

请帮助我使用openmp使这个代码并行这个代码是在按钮点击运行,文本框是128

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace IMG { public partial class Form1 : Form { public Form1() { InitializeComponent(); } string path = ""; public void openimage() { if (openFileDialog1.ShowDialog() == DialogResult.OK) { path = openFileDialog1.FileName; Graphics g = this.CreateGraphics(); g.Clear(this.BackColor); Bitmap curBitmap = new Bitmap(path); g.DrawImage(curBitmap, 200, 220, 200, 200); } } Bitmap bm; Bitmap gs; private void button1_Click(object sender, EventArgs e) { if (path == "") { openimage(); } //mack image gray scale Graphics g = this.CreateGraphics(); g.Clear(this.BackColor); // Create a Bitmap object bm = new Bitmap(path); // Draw image with no effects g.DrawImage(bm, 200, 220, 200, 200); gs = new Bitmap(bm.Width, bm.Height); for (int i = 0; i < bm.Width; i++) { for (int j = 0; j < bm.Height; j++) { Color c = bm.GetPixel(i, j); int y = (int)(0.3 * cR + 0.59 * cG + 0.11 * cB); gs.SetPixel(i, j, Color.FromArgb(y, y, y)); } } // Draw image with no effects g.DrawImage(gs, 405, 220, 200, 200); for (int i = 0; i < gs.Width; i++) { for (int j = 0; j = Convert.ToInt16(textBox19.Text)) y1 = 255; bm.SetPixel(i, j, Color.FromArgb(y1, y1, y1)); } } g.DrawImage(bm, new Rectangle(610, 220, 200, 200), 0, 0, bm.Width, bm.Height, GraphicsUnit.Pixel); // Dispose of objects gs.Dispose(); g.Dispose(); } } } 

一旦你能相信这个网站和所有程序员,请帮助我…

如果OpenMP在您的雷达上,您将遇到几个速度障碍。 OpenMP是一个用于非托管C / C ++的multithreading库,它需要编译器支持才能生效。 不是C#的选项。

我们退一步吧。 你现在得到的就像你可能得到的一样糟糕。 Get / SetPixel()非常慢。 一个主要的步骤是使用Bitmap.LockBits(),它为位图位提供IntPtr。 您可以使用不安全的字节指针对这些位进行聚会。 这将至少快一个数量级。

让我们再退一步,你清楚地编写代码将彩色图像转换为灰度图像。 GDI +通过ColorMatrix类本身支持颜色转换。 该代码可能如下所示:

 public static Image ConvertToGrayScale(Image srce) { Bitmap bmp = new Bitmap(srce.Width, srce.Height); using (Graphics gr = Graphics.FromImage(bmp)) { var matrix = new float[][] { new float[] { 0.299f, 0.299f, 0.299f, 0, 0 }, new float[] { 0.587f, 0.587f, 0.587f, 0, 0 }, new float[] { 0.114f, 0.114f, 0.114f, 0, 0 }, new float[] { 0, 0, 0, 1, 0 }, new float[] { 0, 0, 0, 0, 1 } }; var ia = new System.Drawing.Imaging.ImageAttributes(); ia.SetColorMatrix(new System.Drawing.Imaging.ColorMatrix(matrix)); var rc = new Rectangle(0, 0, srce.Width, srce.Height); gr.DrawImage(srce, rc, 0, 0, srce.Width, srce.Height, GraphicsUnit.Pixel, ia); return bmp; } } 

感谢鲍勃鲍威尔的上述代码。

为什么要将此代码并行? 为了获得处理效率(时间)? 如果是这样,我认为在将此代码并行之前,您可以尝试使用不同的方法来访问图像中的像素信息。

你在这段代码中的表现非常缓慢。 您可能会尝试使用不安全的代码处理图像以访问Bitmap类的像素。

看一下这个post ,看看我在说什么