这是我的位图对象
Bitmap b = new Bitmap(columns, rows, PixelFormat.Format8bppIndexed);
BitmapData bmd = b.LockBits(new Rectangle(0, 0, columns, rows), ImageLockMode.ReadWrite, b.PixelFormat);
Run Code Online (Sandbox Code Playgroud)
如何将其转换为8位灰度位图?
目前,我正在使用该SetPixel()方法来更改位图中每个像素的颜色。这对于小尺寸的小图像效果很好,但是当我在大图像上测试它时,它确实需要一段时间。
我以前没有在 VB.Net 中处理过图像,所以我可能只是忽略了一些明显的东西。我这样做是为了制作一个将图像转换为灰度的程序。这会产生正确的结果,但速度较低,并且在此期间 UI 会冻结,因此我热衷于最大限度地提高转换速度。
这是我目前的代码:
Dim tmpImg As New Bitmap(img) '"img" is a reference to the original image
For x As Integer = 0 To tmpImg.Width - 1
For y As Integer = 0 To tmpImg.Height - 1
Dim clr As Byte
With tmpImg.GetPixel(x, y)
clr = ConvertToGrey(.R, .G, .B)
End With
tmpImg.SetPixel(x, y, Color.FromArgb(clr, clr, clr))
Next
Next
Private Function ConvertToGrey(ByVal R As Byte, ByVal G As Byte, ByVal B As Byte) As Byte
Return …Run Code Online (Sandbox Code Playgroud) 这应该计算8位灰度图像的直方图.使用1024x770测试位图,CreateTime最终在890ms左右.我怎样才能更快地完成这个(方式,方式)?
编辑:我应该提到,这实际上并没有计算直方图,它只从位图中获取值.所以我真的应该问,从8位灰度图像中检索所有像素值的最快方法是什么?
public class Histogram {
private static int[,] values;
public Histogram(Bitmap b) {
var sw = Stopwatch.StartNew();
values = new int[b.Width, b.Height];
for (int w = 0; w < b.Width; ++w) {
for (int h = 0; h < b.Height; ++h) {
values[w, h] = b.GetPixel(w, h).R;
}
}
sw.Stop();
CreateTime = (sw.ElapsedTicks /
(double)Stopwatch.Frequency) * 1000;
}
public double CreateTime { get; set; }
}
Run Code Online (Sandbox Code Playgroud)