poimsm2
poimsm2

Reputation: 562

OpenCV - imencode not working due to few channels

I am trying to create a code to crop and change the perspective of an image. But I'm getting a problem with the conversion of Mat to an array of bytes through imencode. This is my code:

int process_image_bytes(uchar* bytes, int size, uchar **encodedOutput) {
        vector <uchar> v(bytes, bytes + size);
        Mat img = imdecode(Mat(v), IMREAD_COLOR);

        int width = 200;
        int height = 200;

        vector<Point2f> src_p = {
            Point(200, 200), 
            Point(500, 200),
            Point(300, 200),
            Point(500, 300)
        };

        InputArray src_p_arr = src_p;

        vector<Point2f> dst_p = {
            Point(0, 0), 
            Point(width, 0),
            Point(0, height),
            Point(width, height)            
        };

        OutputArray dst_p_arr = dst_p;        

        Mat warpMatrix = getPerspectiveTransform(src_p_arr, dst_p_arr);

        Mat outputImg;        
        warpPerspective(src_p_arr, outputImg, warpMatrix, dst_p_arr.size());        

        vector<uchar> buf;
        imencode(".jpg", outputImg, buf); // <-- Error Happen Here

        *encodedOutput = (unsigned char *) malloc(buf.size());

        for (int i=0; i < buf.size(); i++)
            (*encodedOutput)[i] = buf[i];

       return (int) buf.size();
   }

I'm getting this error:

(Assertion failed) channels == 1 || channels == 3 || channels == 4 in function 'imencode

Why does it happen that outputImg has only 2 channels meanwhile the input image has 3 channels?

I've printed some logs to the console while the code was running:

------ INPUT IMAGE img --------

width::: 720

height::: 405

channels::: 3

type::: 16

depth::: 0

------ WARP MATRIX warpMatrix ------

width::: 3

height::: 3

channels::: 1

type::: 6

depth::: 6

------ DESTINATION dst_p_arr ------

width::: 4

height::: 1

channels::: 2

type::: 13

depth::: 5

------ OUTPUT IMAGE outputImg ------

width::: 4

height::: 1

channels::: 2

type::: 13

depth::: 5

Upvotes: 0

Views: 310

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

The first argument of warpPerspective() has to be the input image, not coordinates that are used to build the matrix.

Also, the forth argument of the function has to be the size of the output image, not the size of coordinates that are used to build the matrix.

In other words, the line

warpPerspective(src_p_arr, outputImg, warpMatrix, dst_p_arr.size());

should be:

warpPerspective(img, outputImg, warpMatrix, Size(width, height));

Upvotes: 2

Related Questions