• 将二值图像存入二值数组


    因项目需要,需要用一个将二值图像保存在二维数组中的算法,在网上找了很久都没找到,只能自己动手写了。

            #region 读取二值图像存入二值数组
    
            public byte[,] BinaryBitmapToBinaryArray(Bitmap bmp)
            {
                int imgWidth = bmp.Width;
                int imgHeight = bmp.Height;
    
                byte[,] BinaryArray = new byte[imgHeight, imgWidth];
                for (int i = 0; i < BinaryArray.GetLength(0); i++)
                {
                    for (int j = 0; j < BinaryArray.GetLength(1); j++)
                    {
                        BinaryArray[i, j] = 1;
                    }
                }
                int depth = Bitmap.GetPixelFormatSize(bmp.PixelFormat);
                if (depth == 1)
                {
                    Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
                    BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, bmp.PixelFormat);
                    int imgStride = bmpData.Stride;
                    //得到首地址
                    IntPtr ptr = bmpData.Scan0;
    
                    //定义被锁定的数组大小,由位图数据与未用空间组成的
                    int bytes = imgStride * imgHeight;
                    //定义位图数组
                    byte[] bmpValues = new byte[bytes];
                    //复制被锁定的位图像素值到该数组内
                    Marshal.Copy(ptr, bmpValues, 0, bytes);
    
                    int basePos = 0;
                    bool isOne = false;
                    for (int y = 0; y < imgHeight; y++)
                    {
                        basePos = y * imgStride;
                        for (int x = 0; x < imgWidth; x ++)
                        {
                            isOne = ByteGetBit(bmpValues[basePos + (x >> 3)], (7-x & 0x7));
                            //ByteGetBit判断一个字节第几位是否是1,该函数是从后往前数的,而这里是从高位向低位数的。所以要用7减去x & 0x7
                            if (isOne)
                            {
                                BinaryArray[y, x] = 255;
                            }
                            else
                            {
                                BinaryArray[y, x] = 0;
                            }
                        }
                    }
                            bmp.UnlockBits(bmpData);
                }
                return BinaryArray;
            } 
    
            #endregion
  • 相关阅读:
    no.5.print sum
    0.1 hint crack
    no.4 抽奖测试
    no2.crossdomain.xml批量读取(待完善)
    no.1
    day7-读写分离
    day6-主从
    day5-备份
    day4-用户授权
    Day3-体系结构+查询+导入/出
  • 原文地址:https://www.cnblogs.com/dearzhoubi/p/9855480.html
Copyright © 2020-2023  润新知