Skip to content

Instantly share code, notes, and snippets.

@ewyuanzhang
Created April 8, 2021 04:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ewyuanzhang/a68cc47545dde91cbb68ba311dbeff8d to your computer and use it in GitHub Desktop.
Save ewyuanzhang/a68cc47545dde91cbb68ba311dbeff8d to your computer and use it in GitHub Desktop.
How to convert OpenCV Mat to SoftwareBitmap with C++/WinRT
#include "pch.h"
#include <winrt/Windows.Security.Cryptography.h>
using namespace winrt;
using namespace winrt::Windows::Storage::Streams;
using namespace winrt::Windows::Graphics::Imaging;
using namespace std;
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
int main()
{
init_apartment();
Mat bgr_image = imread("test_img.bmp", IMREAD_COLOR);
// Add alpha channel
Mat image(bgr_image.size(), CV_8UC4);
Mat alpha(bgr_image.size(), CV_8UC1, 255);
Mat image_in[] = { bgr_image, alpha };
int from_to[] = { 0,0, 1,1, 2,2, 3,3 };
mixChannels(image_in, 2, &image, 1, from_to, 4);
// Convert image data to byte array
vector<uchar> array;
if (image.isContinuous()) {
array.assign(image.data, image.data + image.total() * image.channels());
}
else {
for (int i = 0; i < image.rows; ++i) {
array.insert(array.end(), image.ptr<uchar>(i), image.ptr<uchar>(i) + image.cols * image.channels());
}
}
// Convert byte array to SoftwareBitmap
IBuffer buffer = CryptographicBuffer::CreateFromByteArray( array );
SoftwareBitmap softwareBitmap = SoftwareBitmap::CreateCopyFromBuffer(buffer, BitmapPixelFormat::Bgra8, image.cols, image.rows);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment