Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get encoded image out of cv::imencode (getting mess). How to fix broken saving of .jpg?

So I try to save image into ostream via cv::imencode apis. From imencode we get vector. As shown here it can be stored into any ostream. For example std::ofstream. But it fails currupting data=(

This is what we see:

enter image description here

Here is what we get in file:

enter image description here

And here is our code:

#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <string>
#include <ctime>
#include <iterator>

#include <opencv2/opencv.hpp>



void send_data(std::ostream & o, const std::vector<uchar> & v)
{
    o.write(reinterpret_cast<const char*>(v.data()), v.size());
}

int main(  )
{
    int w=400, h=400;
    cv::Mat black = cv::Mat::zeros(cv::Size(w, h), CV_8UC3);

    {
        for(int i = 0; i <= 35; ++i)
        {
            for (int k = 0; k <=35; ++k)
            {
                black.row(i).col(k) = 255;
            }
        }

        for(int i = 10; i <= 15; ++i)
        {
            for (int k = 10; k <=15; ++k)
            {
                black.row(i).col(k) = 0;
            }
        }

        for(int i = 25; i <= 30; ++i)
        {
            for (int k = 25; k <=30; ++k)
            {
                black.row(i).col(k) = 0;
            }
        }

        for(int i = 25; i <= 75; ++i)
        {
            for (int k = 25; k <= 75; ++k)
            {
                black.row(i).col(k) = 255;
            }
        }

        for(int i = 35; i <= 65; ++i)
        {
            for (int k = 35; k <=65; ++k)
            {
                black.row(i).col(k) = 0;
            }
        }

        for(int i = 57; i <= 62; ++i)
        {
            for (int k = 57; k <=62; ++k)
            {
                black.row(i).col(k) = 255;
            }
        }

        for(int i = 90; i <= 99; ++i)
        {
            for (int k = 90; k <=99; ++k)
            {
                black.row(i).col(k) = 255;
            }
        }
    }


    cv::namedWindow( "Components", CV_WINDOW_AUTOSIZE );
    cv::imshow( "Components", black );

    std::vector<uchar> buff;

    std::vector<int> p;
    p.push_back(CV_IMWRITE_JPEG_QUALITY);
    p.push_back(9);

    cv::imencode(".jpg", black, buff);

    std::ofstream outfile ("test.jpg");
    send_data(outfile, buff);
    outfile.close();

    cv::waitKey(0);
    std::cin.get();
    return 0;
}
like image 870
Rella Avatar asked Nov 04 '22 11:11

Rella


1 Answers

You need to open the output file in binary mode.

std::ofstream outfile ("test.jpg", std::ofstream::binary);
like image 188
Retired Ninja Avatar answered Nov 13 '22 02:11

Retired Ninja