I have an image processing function written in C++ based on opencv. In my wpf application I have used AForge library to access a webcam and update it on UI. This the functio
You can use Bitmap.Save() method to convert it to a memory stream and then send it to C++ dll.
public Image ConvertImage(Image image)
{
MemoryStream convertedImageMemoryStream;
using (MemoryStream sourceImageStream = new MemoryStream())
{
image.Save(sourceImageStream, System.Drawing.Imaging.ImageFormat.Png);
byte[] sourceImageData = sourceImageStream.ToArray();
// Send it to dll and get the IntPtr byte array from dll
byte[] imageData = new byte[imInfo.size];
Marshal.Copy(imInfo.data, imageData, 0, imInfo.size);
if (imInfo.data != IntPtr.Zero)
AlgorithmCpp.ReleaseMemoryFromC(imInfo.data);
convertedImageMemoryStream = new MemoryStream(imageData);
}
Image processed = new Bitmap(convertedImageMemoryStream);
return processed;
}
Then, in C++ dll use decoding such as cv::imdecode() method to get the image.
DllExport void convertToGray(unsigned char* data, int dataLen)
{
vector inputImageBytes(data, data + dataLen);
Mat image = imdecode(inputImageBytes, CV_LOAD_IMAGE_COLOR);
Mat processed;
cvtColor(image, processed, CV_BGR2GRAY);
vector bytes;
imencode(".png", processed, bytes);
// ....
There are some pros in this way such as,
1. fewer data to transfer
2. minimum implementation effort from both C# and C++ end.
3. Does not depend on the source image type eg. color or grayscale or any other color palate type. So it's very safe to use.
The only problem is that it is CPU intensive as there are an encoding and a decoding.
Details are here.