halcon影象變數和C#影象變數的相互轉換
阿新 • • 發佈:2019-01-23
// halcon rgb變數轉C# bitmap變數 public static Bitmap HObject2Bitmap3(HObject ho) { Bitmap bimp = null; HTuple hred, hgreen, hblue, type, width, height; HOperatorSet.GetImagePointer3(ho, out hred, out hgreen, out hblue, out type, out width, out height); bimp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppRgb); Rectangle rect = new Rectangle(0, 0, width, height); BitmapData bitmapData = bimp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb); unsafe { byte* bptr = (byte*)bitmapData.Scan0; byte* r = ((byte*)hred.I); byte* g = ((byte*)hgreen.I); byte* b = ((byte*)hblue.I); for (int i = 0; i < width * height; i++) { bptr[i * 4] = (b)[i]; bptr[i * 4 + 1] = (g)[i]; bptr[i * 4 + 2] = (r)[i]; bptr[i * 4 + 3] = 255; } } bimp.UnlockBits(bitmapData); return bimp; } // halcon gray變數轉C# bitmap變數 public static Bitmap HObject2Bitmap(HObject ho) { try { HTuple type, width, height, pointer; //HOperatorSet.AccessChannel(ho, out ho, 1); HOperatorSet.GetImagePointer1(ho, out pointer, out type, out width, out height); //himg.GetImagePointer1(out type, out width, out height); Bitmap bmp = new Bitmap(width.I, height.I, PixelFormat.Format8bppIndexed); ColorPalette pal = bmp.Palette; for (int i = 0; i <= 255; i++) { pal.Entries[i] = Color.FromArgb(255, i, i, i); } bmp.Palette = pal; BitmapData bitmapData = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed); int PixelSize = Bitmap.GetPixelFormatSize(bitmapData.PixelFormat) / 8; int stride = bitmapData.Stride; int ptr = bitmapData.Scan0.ToInt32(); for (int i = 0; i < height; i++) { CopyMemory(ptr, pointer, width * PixelSize); pointer += width; ptr += bitmapData.Stride; } bmp.UnlockBits(bitmapData); return bmp; } catch (Exception exc) { return null; } } // C# bitmap變數轉為 halcon變數 public static HObject Bitmap2HObject(Bitmap bmp) { try { Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed); IntPtr pointer = bmpData.Scan0; byte[] dataBlue = new byte[bmp.Width * bmp.Height]; unsafe { fixed (byte* ptrdata = dataBlue) { for (int i = 0; i < bmp.Height; i++) { CopyMemory((int)(ptrdata + bmp.Width * i), (int)(pointer + bmpData.Stride * i), bmp.Width); } HObject ho; HOperatorSet.GenImage1(out ho, "byte", bmp.Width, bmp.Height, (int)ptrdata); HImage himg = new HImage("byte", bmp.Width, bmp.Height, (IntPtr)ptrdata); //HOperatorSet.DispImage(ho, hWindowControl1.HalconWindow); bmp.UnlockBits(bmpData); return ho; } } } catch (Exception exc) { return null; } }
此內容為原創,如需轉載請註明出處!