'opencv c++ imgshow is ok but the video I have saved is just black

I use opencv in c++ and I want to save the video about mask. I print it by imgshow and It works.enter image description here

But when I want to save it, it just gives me all black.enter image description here

And I do let my mat*255. Here's part of the code:

    cv::Mat mat;
    unsigned int i = 0;
    VideoWriter writer;
    VideoWriter writer1;
    video_capture >> mat;
    int coder = VideoWriter::fourcc('M', 'P', '4', '2');//选择编码格式
    double fps = 25.0;//设置视频帧率
    string filename = "mattingVedio.mp4";//保存的视频文件名称
    string filename1 = "mattingVedio_mask.mp4";//保存的视频文件名称
    writer.open(filename, coder, fps, mat.size(), true);//创建保存视频文件的视频流
    if (!writer.isOpened()) {
        cout << "fail" << endl;
        return -1;
    }
    writer1.open(filename1, coder, fps, mat.size(), true);//创建保存视频文件的视频流
    if (!writer1.isOpened()) {
        cout << "fail" << endl;
        return -1;
    }
    while (video_capture.read(mat))
    {
        i += 1;
        MattingContent content;
        rvm.detect(mat, content, downsample_ratio);

        string kWinName = "src image";
        kWinName = "Deep learning RobustVideoMatting in ONNXRuntime with pha";
        namedWindow(kWinName, WINDOW_NORMAL);
        imshow(kWinName, content.pha_mat);
        writer.write(content.merge_mat);//把图像写入视频流
        writer1.write(content.pha_mat*255);//把图像写入视频流
        waitKey(1);
    }
    writer.release();
    writer1.release();
    cout << endl << "matting job done!";
    destroyAllWindows();
}

It makes me crazy! Willing your help!



Solution 1:[1]

I got it. The bug do is from type. I convert my type to cv_8U, and it works. Otherwise, the encoding type is also very important, because after I use 'M', 'P', 'E', 'G' and it miss up all things but after I change it to 'P', 'I', 'M', '1' everything goes right. Also I change writer1 :true to false `

writer.write(content.merge_mat);//????????
Mat p,grey;
p = content.pha_mat * 255;
p.convertTo(grey, CV_8U);
writer1.write(grey);//????????

`

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 divergent