- #halcon 转
- public static WriteableBitmap ToWriteableBitmap(this HObject hObject)
- {
- HOperatorSet.GenEmptyObj(out var dataHObject);
- var pixelFormat = PixelFormat.Undefined;
- //判断halcon通道个数
- HOperatorSet.CountChannels(hObject, out var channelCount);
- if (channelCount == 1)
- {
- dataHObject = hObject;
- pixelFormat = PixelFormat.Format8bppIndexed;
- }
- else if (channelCount == 3)
- {
- //把三通道生成交错图片
- HOperatorSet.InterleaveChannels(hObject, out dataHObject, "rgb", "match", 0);
- pixelFormat = PixelFormat.Format24bppRgb;
- }
- HOperatorSet.GetImagePointer1(dataHObject, out var imagePtr, out var type, out var width, out var height);
- if (channelCount == 3)
- {
- width /= 3;
- }
- var strideInfo = new BitmapStrideInfo(width, height, pixelFormat);
- WriteableBitmap writeableBitmap = null;
- if (channelCount == 1)
- {
- writeableBitmap =
- new WriteableBitmap(width, height, 96, 96, PixelFormats.Indexed8, BitmapPalettes.Gray256);
- }
- else if(channelCount == 3)
- {
- writeableBitmap =
- new WriteableBitmap(width, height, 96, 96, PixelFormats.Rgb24, null);
- }
- else
- {
- throw new NotImplementedException($"{channelCount}通道数暂不支持");
- }
- try
- {
- writeableBitmap.Lock();
- unsafe
- {
- var readSpan = new Span<byte>(imagePtr.IP.ToPointer(), strideInfo.EfficientTotalSize);
- var writeSpan = new Span<byte>(writeableBitmap.BackBuffer.ToPointer(), strideInfo.Stride * strideInfo.Height);
- for (int i = 0; i < strideInfo.Height; i++)
- {
- readSpan.Slice(i * strideInfo.EfficientPerRowBytes, strideInfo.EfficientPerRowBytes)
- .CopyTo(writeSpan.Slice(i * strideInfo.Stride, strideInfo.EfficientPerRowBytes));
- }
- }
- writeableBitmap.AddDirtyRect(new Int32Rect(0,0,width,height));
- return writeableBitmap;
- }
- finally
- {
- writeableBitmap.Unlock();
- }
- }
复制代码 |