VisionAPI.cs 27.0 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Security.Permissions;
using System.Threading;
using log4net;
using System.Windows.Forms;

namespace paddleOCR
{

    #region 结构体
    // 图像信息
    [StructLayout(LayoutKind.Sequential)]
    public struct EyemImage
    {
        public IntPtr vpImage;                     // 地址
        public int iWidth;                         // 图像内存 x 方向大小
        public int iHeight;                        // 图像内存 y 方向大小
        public int iDepth;                         // 图像位深度(详见说明)
        public int iChannels;                      // 图像通道数
    }

    // 矩形定义
    [StructLayout(LayoutKind.Sequential)]
    public struct EyemRect
    {
        public int iXs;                            // 起始点(左上角) x 坐标
        public int iYs;                            // 起始点(左上角) y 坐标
        public int iWidth;                         // x 方向大小(宽度)
        public int iHeight;                        // y 方向大小(高度)
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemRect2
    {
        public int iXs;                            // 起始点(左上角) x 坐标
        public int iYs;                            // 起始点(左上角) y 坐标
        public int iXe;                            // 端点(右下) x 坐标
        public int iYe;                            // 端点(右下) y 坐标
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemRect3
    {
        public int iXs;                            // 起始点(左上角) x 坐标
        public int iYs;                            // 起始点(左上角) y 坐标
        public int iWidth;                         // x 方向大小(宽度)
        public int iHeight;                        // y 方向大小(高度)
        public double dVar;                        // 某种可能会使用的值
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct BboxContainer
    {
        //最多支持100个目标
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 100)]
        public EyemRect[] bboxes;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct RotateBox
    {
        //最多支持25个目标
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 25)]
        public EyemOcsIXY[] p1;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 25)]
        public EyemOcsIXY[] p2;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 25)]
        public EyemOcsIXY[] p3;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 25)]
        public EyemOcsIXY[] p4;
    }

    ///////////////////////////////////////////////////////////////////////////////
    // Orthogonal Coordinate System

    /////////////////////
    // int type
    //
    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsIXY
    {
        public int iX;                             // X坐标
        public int iY;                             // Y坐标
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsIXYZ
    {
        public int iX;                             // X坐标
        public int iY;                             // Y坐标
        public int iZ;                             // Z坐标
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsIXYQ
    {
        public int iX;                             // X坐标
        public int iY;                             // Y坐标
        public int iQ;                             // θ
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsIXYR                      // 用于表示圆
    {
        public int iX;                             // X坐标
        public int iY;                             // Y坐标
        public int iR;                             // 半径
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsIABC                      // 用于表示直线(一般形式)
    {
        public int iA;                             // a
        public int iB;                             // b
        public int iC;                             // c
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsIRQ                       // 用于表示直线(黑森标准形式)或矢量
    {
        public int iR;                             // ρ
        public int iQ;                             // θ
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsIXYQS
    {
        public int iX;                             // X坐标(单位:像素)
        public int iY;                             // Y坐标(单位:像素)
        public int iQ;                             // 斜率(単位:rad)
        public int iS;                             // 刻度
    }


    /////////////////////
    // float type
    //
    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsFXY
    {
        public float fX;                           // X坐标
        public float fY;                           // Y坐标
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsFXYZ
    {
        public float fX;                           // X坐标
        public float fY;                           // Y坐标
        public float fZ;                           // Z坐标
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsFXYQ
    {
        public float fX;                           // X坐标
        public float fY;                           // Y坐标
        public float fQ;                           // θ
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsFXYR                      // 用于表示圆
    {
        public float fX;                           // X坐标
        public float fY;                           // Y坐标
        public float fR;                           // 半径
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsFABC                      // 用于表示直线(一般形式)
    {
        public float fA;                           // a
        public float fB;                           // b
        public float fC;                           // c
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsFRQ                       // 用于表示直线(黑森标准形式)或矢量
    {
        public float fR;                           // ρ
        public float fQ;                           // θ
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsFXYQS
    {
        public float fX;                           // X坐标(単位:像素)
        public float fY;                           // Y坐标(単位:像素)
        public float fQ;                           // 斜率(単位:rad)
        public float fS;                           // 刻度
    }


    /////////////////////
    // double type
    //
    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsDXY
    {
        public double dX;                          // X坐标
        public double dY;                          // Y坐标
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsDXYZ
    {
        public double dX;                          // X坐标
        public double dY;                          // Y坐标
        public double dZ;                          // Z坐标
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsDXYQ
    {
        public double dX;                          // X坐标
        public double dY;                          // Y坐标
        public double dQ;                          // θ
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsDXYR                      // 用于表示圆
    {
        public double dX;                          // 中心的X坐标
        public double dY;                          // 中心的Y坐标
        public double dR;                          // 半径
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsDABC                      // 直线(一般形)的表现形式
    {
        public double dA;                          // a
        public double dB;                          // b
        public double dC;                          // c
    }


    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsDRQ                       // 用于表示直线(黑森标准形状)和矢量
    {
        public double dR;                          // ρ
        public double dQ;                          // θ
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsDXYQS
    {
        public double dX;                          // X坐标
        public double dY;                          // Y坐标
        public double dQ;                          // 旋转角度(単位:rad)
        public double dS;                          // 规模
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsDABCD                     // 用于表示平面(一般形式)
    {
        public double dA;                          // a
        public double dB;                          // b
        public double dC;                          // c
        public double dD;                          // d
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsDXYLSQ                    // 用于表示椭圆
    {
        public double dXo;                         // 中心X坐标
        public double dYo;                         // 中心Y坐标
        public double dL;                          // 长轴半径
        public double dS;                          // 短轴半径
        public double dQ;                          // 长轴倾斜角(単位:rad)
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsDPV                       // 用于表示三维空间中的直线
    {
        public EyemOcsDXYZ tP;                     // 直线上一点的坐标
        public EyemOcsDXYZ tV;                     // 直线方向矢量
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemOcsDCRUVW                    // 用于表示椭圆体
    {
        public EyemOcsDXYZ tC;                     // 椭圆体中心
        public EyemOcsDXYZ tR;                     // 轴半径(dX:长轴、dY:中轴、dZ:短轴)
        public double dU;                          // 长轴投影到 XY 平面与 X 轴的角(单位:rad)
        public double dV;                          // 长轴与XY平面之角(单位:rad)
        public double dW;                          // 绕长轴旋转角度(单位:rad)
    }

    // Blob 分析结果
    [StructLayout(LayoutKind.Sequential)]
    public struct EyemBinBlob
    {
        public int iLabel;                          // 标签
        public int iArea;                           // 面积
        public double dCenterX;                     // 重心x坐标
        public double dCenterY;                     // 重心y坐标
        public int iXs, iYs, iXe, iYe;              // 外接矩形(始点,终点)
        public int iWidth, iHeight;                 // 外接矩形(x 方向大小(宽度),y 方向大小(高度))
        public double dTheta;                       // 主轴倾斜角(rad)
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemChainCode
    {
        public int iLabel;                         // 标签
        public double dX;                          // x坐标
        public double dY;                          // y坐标
        public double dVx, dVy;                    // 向量
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemBlobParams
    {
        // public bool isLight;
        public bool filterByArea;                         //斑点大小限制
        public int minArea, maxArea;                      //最小面积/最大面积
        public bool filterByCircularity;                  //斑点圆度限制
        public float minCircularity, maxCircularity;      //圆度最小/大限制
        public bool filterByInertia;                      //斑点的惯性率限制
        public float minInertiaRatio, maxInertiaRatio;    //惯性率最小/大限制
        public bool filterByConvexity;                    //斑点凸度限制
        public float minConvexity, maxConvexity;          //凸度最小/大限制
    }

    // 条码 解码结果
    [StructLayout(LayoutKind.Sequential)]
    public struct EyemBarCode
    {
        public double dAngle;                      // 角度
        public int iCenterX;                       // x坐标
        public int iCenterY;                       // y坐标
        public IntPtr hType;                       // 码类型
        public IntPtr hText;                       // 码内容
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemModelID
    {
        public IntPtr vpImage;                     // 地址
        public int iXs;                            // 图像X坐标
        public int iYs;                            // 图像Y坐标
        public int iWidth;                         // 图像内存X方向大小
        public int iHeight;                        // 图像内存Y方向大小
        public double dMatchDeg;                   // 匹配度
        public IntPtr lpszName;                    // 名称
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct EyemRigidMatrix
    {
        public double a00;                         // a00
        public double a01;                         // a01
        public double b00;                         // b00
        public double a10;                         // a10
        public double a11;                         // a11
        public double b10;                         // b10
    }


    [StructLayout(LayoutKind.Sequential)]
    public struct EyemHSVModel
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
        public double[] dpRangeL, dpRangeU;        // 提取下限,提取上限[H S V]
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
        public double[] dpRangeLExt, dpRangeUExt;  // 额外提取下限,额外提取上限(针对处于跨模型颜色,比如红色)[H S V]
    }// 用于HSV颜色模型分割(H(0-180)、S(0-255)、V(0-255))


    [StructLayout(LayoutKind.Sequential)]
    public struct EyemTargetMatch
    {
        public float fCenterX;
        public float fCenterY;
        public float fMatchScore;
        public float fMatchAngle;
    }

    #endregion
    public unsafe partial class VisionAPI
    {
        #region 通用
        /// <summary>
        /// Win32 memory copy function
        /// </summary>
        /// <param name="dst">目标地址</param>
        /// <param name="src">源地址</param>
        /// <param name="count">长度</param>
        /// <returns></returns>
        [DllImport("ntdll.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern byte* memcpy(byte* dst, byte* src, int count);
        /// <summary>
        /// 从进程中的非托管内存分配指定长度的内存
        /// </summary>
        /// <param name="cb">长度</param>
        /// <returns>指向新分配的内存指针</returns>
        [DllImport("eyemLib.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern IntPtr eyemMallocMemBlock(int cb);
        /// <summary>
        /// 释放以前从非托管内存中分配的内存
        /// </summary>
        /// <param name="block">地址</param>
        [DllImport("eyemLib.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern void eyemFreeMemBlock(IntPtr block);
        /// <summary>
        /// 读取图像文件
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <param name="iFlags">读取标志,-1:按照原样加载图像 0:始终将图像转化成单通道灰度图像 1:如果设置,请始终将图像转换为3通道BGR彩色图像
        /// 2:在输入具有相应深度时返回16位/32位图像,否则将其转换为8位 4:以任何可能的颜色格式读取图像 </param>
        /// <param name="tpImage">图像</param>
        /// <returns></returns>
        [DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
        public static extern int eyemImageRead(string filename, int iFlags, out EyemImage tpImage);
        /// <summary>
        /// 释放图像资源
        /// </summary>
        /// <param name="tpImage">图像</param>
        [DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
        public static extern void eyemImageFree(ref EyemImage tpImage);
        #endregion

        #region 深度学习目标检测器
        /// <summary>
        /// 初始化检测器
        /// </summary>
        /// <param name="detectorConfigPath">配置文件</param>
        /// <param name="detectorModelPath">模型文件</param>
        /// <returns></returns>
        [DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
        public static extern int eyemInitNNDetector(string detectorConfigPath, string detectorModelPath, int iNetSizew, int iNetSizeh);
        /// <summary>
        /// 设置检测参数
        /// </summary>
        /// <param name="fConfidence">置信度</param>
        /// <param name="fNMSThreshold">非极大值抑制阈值</param>
        /// <returns></returns>
        [DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
        public static extern int eyemNNDetectorParams(float fConfidence, float fNMSThreshold);
        /// <summary>
        /// 目标检测器
        /// </summary>
        /// <param name="tpImage">输入图像</param>
        /// <returns></returns>
        [DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
        public static extern int eyemNNDetector(EyemImage tpImage, out int ipNum, ref BboxContainer container, out EyemImage tpDstImg);

        //实例分割
        [DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
        public static extern int eyemNNInstanceSegment(EyemImage tpImage,float fThreshold, ref RotateBox container, out EyemImage tpDstImg);
        //public static extern int eyemNNInstanceSegment(EyemImage tpImage, ref RotateBox container, out EyemImage tpDstImg);
        //获取旋转图像
        [DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
        public static extern int eyemAchvRotateImage(EyemImage tpImage, EyemOcsIXY p1, EyemOcsIXY p2, EyemOcsIXY p3, EyemOcsIXY p4, out EyemImage tpDstImg);
        #endregion

        #region OCR识别
        #endregion
        public static log4net.ILog log = LogManager.GetLogger("ocrService");
        static string baseDir = ".\\LabelOut\\";
        static System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
        //public static bool OCRHandle(string imgPath, out string result)
        //{
        //    sw.Restart();
        //    result = "";
        //    if (string.IsNullOrEmpty(imgPath))
        //    {
        //        return false;
        //    }
        //    if (Directory.Exists(baseDir))
        //    {
        //        Directory.Delete(baseDir, true);
        //    }
        //    Directory.CreateDirectory(baseDir);


        //    EyemImage image = new EyemImage();
        //    EyemImage tpDstImg = new EyemImage();
        //    int flag;
        //    log.Info($"准备读取图像:{imgPath}");
        //    flag = eyemImageRead(imgPath, -1, out image);
        //    log.Info($"读取图像:{imgPath},rtnCode={flag}");
        //    ///实例分割
        //    ///
        //    {
        //        RotateBox container = new RotateBox();
        //        flag = eyemNNInstanceSegment(image, ref container, out tpDstImg);
        //        log.Info($"标签分割完成,rtncode={flag}");
        //        Bitmap b = eyemCvtToBitmap(tpDstImg);
        //        log.Info($"转换为Bitmap");
        //        b?.Save($"labelSplit.jpg", ImageFormat.Jpeg);
        //        log.Info($"保存分割结果图:labelSplit.jpg");
        //        eyemImageFree(ref tpDstImg);
        //        List<Task> tasks = new List<Task>();
        //        for (int i = 0; i < 25; i++)
        //        {

        //            EyemImage tpDstImg1 = new EyemImage();
        //            if (i < container.p1.Length && container.p1[i].iX != 0)
        //            {
        //                flag = eyemAchvRotateImage(image, container.p1[i], container.p2[i], container.p3[i], container.p4[i], out tpDstImg1);
        //                Bitmap lbl = eyemCvtToBitmap(tpDstImg1);
        //                lbl?.Save($"{baseDir}label{i}_1.jpg", ImageFormat.Jpeg);
        //                lbl?.RotateFlip(RotateFlipType.Rotate180FlipNone);
        //                lbl?.Save($"{baseDir}label{i}_2.jpg", ImageFormat.Jpeg);
        //                log.Info($"获取标签图像并保存:{baseDir}label{i}");
        //                eyemImageFree(ref tpDstImg1);
        //            }

        //        }
        //        eyemImageFree(ref image);
        //    }


        //    sw.Stop();
        //    log.Info($"分隔标签耗时:{sw.ElapsedMilliseconds}ms");
        //    //OCR识别
        //    List<StringBuilder> sb = new List<StringBuilder>();
        //    //eyemInitOCRRecognizer("./config.txt");

        //    sw.Restart();
        //    DirectoryInfo directoryInfo = new DirectoryInfo(baseDir);
        //    var files = directoryInfo.GetFiles();
        //    if (files != null && files.Length == 0)
        //    {
        //        log.Info($"无分割的标签,将原图传入名为label.jpg");
        //        byte[] bytes;
        //        using (FileStream fs = new FileStream(imgPath, FileMode.Open))
        //        {
        //            bytes = new byte[fs.Length];
        //            fs.Read(bytes, 0, bytes.Length);
        //        }
        //        MemoryStream memoryStream = new MemoryStream(bytes);
        //        Bitmap bitmap = new Bitmap(memoryStream);
        //        bitmap.Save($"{baseDir}label.jpg");
        //    }
        //    log.Info($"开始OCR识别");
        //    IntPtr ptr = Marshal.AllocHGlobal(1024);
        //    int rtn = eyemOCRRecognizer(baseDir, ref ptr);
        //    log.Info($"OCR识别完成:rtnCode={rtn}");
        //    sw.Stop();
        //    log.Info("识别耗时:" + sw.ElapsedMilliseconds.ToString() + "ms");
        //    string[] strs = Marshal.PtrToStringAnsi(ptr).Replace("\r", "").Split('\n');
        //    Marshal.FreeHGlobal(ptr);
        //    foreach (string str in strs)
        //    {
        //        if (string.IsNullOrEmpty(str)) continue;
        //        if (str.Contains(baseDir)) continue;
        //        result += str + ",";
        //    }
        //    if (result.EndsWith(","))
        //    {
        //        result = result.Substring(0, result.Length - 1);
        //    }
        //    log.Info("识别结果:" + result);
        //    return rtn == 0;
        //}
        public static Bitmap eyemCvtToBitmap(EyemImage tpImage)
        {
            if (tpImage.vpImage == IntPtr.Zero || tpImage.iDepth != 0)
                return null;
            PixelFormat format;
            switch (tpImage.iChannels)
            {
                case 1:
                    format = PixelFormat.Format8bppIndexed;
                    break;
                case 3:
                    format = PixelFormat.Format24bppRgb;
                    break;
                case 4:
                    format = PixelFormat.Format32bppArgb;
                    break;
                default:
                    return null;
            }

            Bitmap bitmap = new Bitmap(tpImage.iWidth, tpImage.iHeight, format);
            //对于输出灰度图像
            if (format == PixelFormat.Format8bppIndexed)
            {
                ColorPalette palette = bitmap.Palette;
                for (int i = 0; i < 256; i++)
                {
                    palette.Entries[i] = Color.FromArgb(i, i, i);
                }
                bitmap.Palette = palette;
            }
            //锁定数据区
            BitmapData bd = bitmap.LockBits(new Rectangle(0, 0, tpImage.iWidth, tpImage.iHeight),
                ImageLockMode.WriteOnly, format);
            try
            {
                int pd = ((tpImage.iWidth * tpImage.iChannels) + 3) / 4 * 4;
                long bytesToCopy = tpImage.iWidth * tpImage.iChannels;
                for (int y = 0; y < tpImage.iHeight; y++)
                {
                    long offsetSrc = (y * tpImage.iWidth * tpImage.iChannels);
                    long offsetDst = (y * pd);
                    Buffer.MemoryCopy((byte*)(tpImage.vpImage.ToPointer()) + offsetSrc, (byte*)(bd.Scan0.ToPointer()) + offsetDst, bytesToCopy, bytesToCopy);
                }
            }
            finally
            {
                bitmap.UnlockBits(bd);
            }
            return bitmap;
        }
        public static EyemImage eyemCvtToEyemImage2(Bitmap bitmap)
        {
            EyemImage tpImage = new EyemImage();
            //锁定数据区
            BitmapData bd = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                ImageLockMode.ReadOnly, bitmap.PixelFormat);

            switch (bitmap.PixelFormat)
            {
                case PixelFormat.Format8bppIndexed:
                    tpImage.iChannels = 1;
                    break;
                case PixelFormat.Format24bppRgb:
                    tpImage.iChannels = 3;
                    break;
                case PixelFormat.Format32bppArgb:
                    tpImage.iChannels = 4;
                    break;
                default:
                    throw new Exception("Image formats are not supported");
            }
            //仅支持8位
            tpImage.iDepth = 0;
            //图像尺寸
            tpImage.iWidth = bitmap.Width; tpImage.iHeight = bitmap.Height;
            //分配内存
            tpImage.vpImage = eyemMallocMemBlock(bd.Stride * bd.Height);
            try
            {
                int pd = ((tpImage.iWidth * tpImage.iChannels) + 3) / 4 * 4;
                long bytesToCopy = tpImage.iWidth * tpImage.iChannels;
                for (int y = 0; y < tpImage.iHeight; y++)
                {
                    long offsetSrc = y * pd;
                    long offsetDst = y * tpImage.iWidth * tpImage.iChannels;
                    Buffer.MemoryCopy((byte*)(bd.Scan0.ToPointer()) + offsetSrc, (byte*)(tpImage.vpImage.ToPointer()) + offsetDst, bytesToCopy, bytesToCopy);
                }
            }
            finally
            {
                bitmap.UnlockBits(bd);
            }
            return tpImage;
        }
    }
}