Getting distorted images after sending them from C # to OpenCV in C ++?

I created a C DLL from my C ++ class, which uses OpenCVimage processing and wants to use this DLL in my C # application. Currently, I have done so:

#ifdef CDLL2_EXPORTS
#define CDLL2_API __declspec(dllexport)
#else
#define CDLL2_API __declspec(dllimport)
#endif

#include "../classification.h" 
extern "C"
{
    CDLL2_API void Classify_image(unsigned char* img_pointer, unsigned int height, unsigned int width, char* out_result, int* length_of_out_result, int top_n_results = 2);
    //...
}

C # code:

DLL import section:

//Dll import 
[DllImport(@"CDll2.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
static extern void Classify_Image(IntPtr img, uint height, uint width, byte[] out_result, out int out_result_length, int top_n_results = 2);

Actual function to send image to DLL:

//...
//main code 
private string Classify(int top_n)
{
    byte[] res = new byte[200];
    int len;
    Bitmap img = new Bitmap(txtImagePath.Text);
    BitmapData bmpData = img.LockBits(new Rectangle(0, 0, img.Width, img.Height), 
                                      ImageLockMode.ReadWrite,  
                                      PixelFormat.Format24bppRgb);
    Classify_Image(bmpData.Scan0, (uint)bmpData.Height, (uint)bmpData.Width, res, out len, top_n);
    img.UnlockBits(bmpData); //Remember to unlock!!!
    //...
}

and C ++ code in a DLL:

CDLL2_API void Classify_Image(unsigned char* img_pointer, unsigned int height, unsigned int width,
                              char* out_result, int* length_of_out_result, int top_n_results)
    {
        auto classifier = reinterpret_cast<Classifier*>(GetHandle());

        cv::Mat img = cv::Mat(height, width, CV_8UC3, (void*)img_pointer, Mat::AUTO_STEP);

        std::vector<Prediction> result = classifier->Classify(img, top_n_results);

        //...
        *length_of_out_result = ss.str().length();
    }

This works fine with some images, but doesn’t work with others, for example, when I try to imshowimage in Classify_Image, right after creating from the data sent by the C # application, I encounter the images as follows:

Problem Example:

enter image description here

Great example:

enter image description here

+4
source share
1 answer

, . , , , , .

:

resolution width * bit-depth (in bytes) * num of channels + padding

bitmap :

- ( ),

, , 1414 , 8- RGB, , :

1414 * 1 * 3 (we have RGB so 3 channels) = 4242 bytes

, 4 :

4242 / 4 = 1060.5

, 0.5 * 4 bytes = 2 bytes padding

, 4244 .

, , .

, , DLL openCV, imdecode, , , cv::IMREAD_GRAYSCALE, .

+2

All Articles