zoukankan      html  css  js  c++  java
  • 【原创】从图像转换到byte[]数组的几种方法

    // 性能最高,其数组和像素一一对应
    public static void test1(Image img)
            {
                Bitmap bmp 
    = new Bitmap(img);
                BitmapData bitmapData 
    = bmp.LockBits(new Rectangle(new Point(00), img.Size), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

                
    byte[] BGRValues = new byte[bitmapData.Stride * bitmapData.Height];

                IntPtr Ptr 
    = bitmapData.Scan0;
                System.Runtime.InteropServices.Marshal.Copy(Ptr, BGRValues, 
    0, BGRValues.Length);

                bmp.UnlockBits(bitmapData);
            }

    // 性能较低,数组内容较少,内容未知
            public static void test2(Image img)
            {
                System.Drawing.ImageConverter ic 
    = new System.Drawing.ImageConverter();
                
    byte[] btImage1 = new byte[0];
                btImage1 
    = (byte[])ic.ConvertTo(img, btImage1.GetType());
            }

    // 性能较低,数组内容为图片格式内容,格式未知
            public static void test3(Image img)
            {
                System.IO.MemoryStream ms 
    = new System.IO.MemoryStream();
                img.Save(ms,ImageFormat.Bmp);
                
    byte[] byteImage = new Byte[0];
                byteImage 
    = ms.ToArray();
            }

    下面说说他们的特点

    test1和test3性能十分接近,test2性能要比前2个明显低一些,应为它们都是内存操作,当然快了。

    test3在单次各种测试候都比test1要快一点点,真的是一点点,但是在做5000次测试时,test3就明显拉开了距离;

    那么可以看出test3在某条语句上耗时了,但可能不是数组操作,比较在内存里,我个人认为是ImageFormat编码的耗时,当然,你用ImageFormat.Png获得的byte[]长度明显变短,

    但是耗时也明显增加。

    test2一如既往的明显慢。

    接着我用了2*2的图片做测试,查看数组内容,有18个长度,test1的BitmapData是非常清晰的,包含bitmapData.Stride的部分,像素BGR排列。

    其他2个的数组内容我个人都看不明白,呵呵,有兴趣的朋友也测试下。

    test2的数组长度明显很短,不怎么明白。

    下面我需要用他们做一些图片比较的工作,当然test1是首选,我很久以前就做好了这个类,使用数组值的突然死亡法,比test2计算hash值后比较的速度好太多了。

    http://www.codeproject.com/dotnet/comparingimages.asp的算法使用了test2的方法,他说性能不错,这个我测试过了,比我慢太多了。

    hash是个不错的想法,test2很短的数组值对于计算hash本身应该有优势。

    那么: test2 时间 + test2 短数组 hash时间 <= test1 时间 + test1 标准像素数组 hash 时间   ???

    这个需要测试,在我的一些应该中,将出现多次的图像比对,对时间要求非常高,选择哪种方法,就取决于耗时。

    可以想象的是,没有了突然死亡法的全数组hash,是没有长远的出路的。。。

  • 相关阅读:
    天梯赛5-12 愿天下有情人都是失散多年的兄妹 【dfs】
    poj2718 Smallest Difference【贪心】
    HDU problem 5635 LCP Array【思维】
    codeforces 782C Andryusha and Colored Balloons【构造】
    HDU 4278 Faulty Odometer【进制转换】
    codeforces B. The Meeting Place Cannot Be Changed【二分】
    POJ 3264 Balanced Lineup 【线段树】
    HDU 1850
    CodeForces-714C
    HDU Problem 1247 Hat's Words 【字典树】
  • 原文地址:https://www.cnblogs.com/keyrratuff/p/1388009.html
Copyright © 2011-2022 走看看