无法从cv :: imencode中获取编码图像(变得混乱)。如何修复.jpg的破损保存?

时间:2011-11-16 00:16:03

标签: c++ image opencv save jpeg

所以我尝试通过cv::imencode apis将图片保存到ostream。从imencode我们得到了矢量。作为shown here,它可以存储到任何ostream中。例如std::ofstream。但它没有破坏数据=(

这就是我们所看到的:

enter image description here

以下是我们收到的文件:

enter image description here

这是我们的代码:

#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;
}

1 个答案:

答案 0 :(得分:2)

您需要以二进制模式打开输出文件。

std::ofstream outfile ("test.jpg", std::ofstream::binary);