首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BitLock-GetPixels时间与PixelFormat

BitLock-GetPixels时间与PixelFormat
EN

Stack Overflow用户
提问于 2014-05-05 03:30:34
回答 1查看 472关注 0票数 0

好吧,我已经创建了两个程序。一个使用GetPixels,另一个使用LockBits。我的GetPixels程序如下..。

所指的条纹图片是200x200 jpg。

代码语言:javascript
复制
Stopwatch GetTime = new Stopwatch();

Bitmap img = new Bitmap("stripe.jpg");
GetTime.Start();
for (int i = 0; i < img.Width; i++)
{
  for (int j = 0; j < img.Height; j++)
   {
     Color pixel = img.GetPixel(i, j);
     output += " " + pixel;
   }
}
GetTime.Stop();

现在,这个读取大约20秒来处理这个图像并输出所有像素。很好,但理论上我的LockBits应该更快一些。我的LockBits代码是..。

代码语言:javascript
复制
Bitmap bmp = new Bitmap("stripe.jpg");


Rectangle bmpRec = new Rectangle(0, 0, bmp.Width, bmp.Height); //Creates Rectangle for holding picture

BitmapData bmpData = bmp.LockBits(bmpRec, ImageLockMode.ReadWrite, Pixels); //Gets the Bitmap data

IntPtr Pointer = bmpData.Scan0; //Scans the first line of data

int DataBytes = Math.Abs(bmpData.Stride) * bmp.Height; //Gets array size

byte[] rgbValues = new byte[DataBytes]; //Creates array

string Pix = " ";

Marshal.Copy(Pointer, rgbValues, 0, DataBytes); //Copies of out memory

bmp.UnlockBits(bmpData);



Stopwatch Timer = new Stopwatch();

pictureBox1.Image = bmp;

Timer.Start();
for (int p = 0; p < DataBytes; p++)
{
    Pix += " " + rgbValues[p];
}
Timer.Stop();

时间是37秒。现在我不明白为什么我花在洛克比上的时间比GetPixels长。

而且,我的输出文件在列出的位置上不匹配。就好像他们是不正常的。

这是一个需要解决的大问题,所以提前感谢大家阅读并试图解决我的问题。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-05 04:20:48

你有几个问题我看得出来。最大的问题是您的图像宽度为200,但在内存中,它的步幅是600 (对我来说--可能与您类似)。这意味着您正在写出更多的数据,因为您不会忽略每行400个填充像素。

其他问题:

  1. 您只需要定时字符串连接。当你启动计时器的时候,锁的东西已经完成了。
  2. 使用StringBuilder,您的字符串连接会更快。
  3. 当您只需要读取时,您正在锁定读/写访问的位图。对于我来说,这个图像对性能没有明显的影响,但还是可以将其更改为ReadOnly。
  4. 大多数注释充其量都是不必要的(// creates array)- -有些是误导性的(//Scans the first line of data -不,它返回一个指向已经加载的数据的指针)。

下面的代码在我的机器上仅在几毫秒内完成。

代码语言:javascript
复制
Bitmap bmp = new Bitmap(@"d:\stripe.jpg");
//pictureBox1.Image = bmp;

Stopwatch Timer = new Stopwatch();

Rectangle bmpRec = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bmpData = bmp.LockBits(
    bmpRec, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
IntPtr Pointer = bmpData.Scan0;
int DataBytes = Math.Abs(bmpData.Stride) * bmp.Height;
byte[] rgbValues = new byte[DataBytes];
Marshal.Copy(Pointer, rgbValues, 0, DataBytes);
bmp.UnlockBits(bmpData);

StringBuilder pix = new StringBuilder(" ");
Timer.Start();
for (int i = 0; i < bmpData.Width; i++)
{
    for (int j = 0; j < bmpData.Height; j++)
    {
        // compute the proper offset into the array for these co-ords
        var pixel = rgbValues[i + j*Math.Abs(bmpData.Stride)];
        pix.Append(" ");
        pix.Append(pixel);
    }
}
Timer.Stop();

Console.WriteLine(Timer.Elapsed);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23464339

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档