0
votes

Suppose we have the following color:

const Scalar TRANSPARENT2 = Scalar(255, 0, 255,0);

which is magenta but fully transparent: alpha = 0 (to be fully opaque is 255).

Now I made the following test based on:

http://blogs.msdn.com/b/lucian/archive/2015/12/04/opencv-first-version-up-on-nuget.aspx

WriteableBitmap^ Grabcut::TestTransparent()
{
Mat res(400,400, CV_8UC4);
res.setTo(TRANSPARENT2);

WriteableBitmap^ wbmp = ref new WriteableBitmap(res.cols, res.rows);
IBuffer^ buffer = wbmp->PixelBuffer;
unsigned char* dstPixels;
ComPtr<IBufferByteAccess> pBufferByteAccess;
ComPtr<IInspectable> pBuffer((IInspectable*)buffer);
pBuffer.As(&pBufferByteAccess);
pBufferByteAccess->Buffer(&dstPixels);
memcpy(dstPixels, res.data, res.step.buf[1] * res.cols * res.rows);
return wbmp;
}

The issue I have is that the image created is not fully transparent, it has a bit of alpha:

enter image description here

I understand there is a fila in the memcpy data, but I am not really sure about how to solve this. any idea to get it to alpha 0?

more details

enter image description here

To see I saving the image could then read and test if it works, I saw that the imwrite contains an snippet about transparency like in the image, but well imwrite is not implemented yet. But the transparency method is not working neither.

Any light with this snippet?

Thanks.

1

1 Answers

0
votes

Finally I did the conversion in the C# code, first avoid calling CreateAlphaMat. Then what I did is use a BitmapEncoder to convert data:

WriteableBitmap wb = new WriteableBitmap(bitmap.PixelWidth, bitmap.PixelHeight);
        using (IRandomAccessStream stream = new InMemoryRandomAccessStream())
        {
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
            Stream pixelStream = bitmap.PixelBuffer.AsStream();
            byte[] pixels = new byte[pixelStream.Length];
            await pixelStream.ReadAsync(pixels, 0, pixels.Length);

            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied,
                        (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 96.0, 96.0, pixels);
            await encoder.FlushAsync();
            wb.SetSource(stream);
        }
        this.MainImage.Source = wb;

where bitmap is the WriteableBitmap from the OpenCV result. And now the image is fully transparent.

NOTE: Do not use MemoryStream and then .AsRandomAccessStream because it won't FlushAsync