opencv/samples/cpp/tutorial_code/snippets/imgcodecs_imwrite.cpp

55 lines
1.5 KiB
C++
Raw Normal View History

#include <opencv2/imgcodecs.hpp>
2017-12-31 19:13:13 +08:00
using namespace cv;
using namespace std;
2020-07-02 04:50:09 +08:00
static void paintAlphaMat(Mat &mat)
2017-12-31 19:13:13 +08:00
{
CV_Assert(mat.channels() == 4);
for (int i = 0; i < mat.rows; ++i)
{
for (int j = 0; j < mat.cols; ++j)
{
Vec4b& bgra = mat.at<Vec4b>(i, j);
bgra[0] = UCHAR_MAX; // Blue
bgra[1] = saturate_cast<uchar>((float (mat.cols - j)) / ((float)mat.cols) * UCHAR_MAX); // Green
bgra[2] = saturate_cast<uchar>((float (mat.rows - i)) / ((float)mat.rows) * UCHAR_MAX); // Red
bgra[3] = saturate_cast<uchar>(0.5 * (bgra[1] + bgra[2])); // Alpha
}
}
}
int main()
{
2020-07-02 04:50:09 +08:00
Mat mat(480, 640, CV_8UC4); // Create a matrix with alpha channel
paintAlphaMat(mat);
2017-12-31 19:13:13 +08:00
vector<int> compression_params;
compression_params.push_back(IMWRITE_PNG_COMPRESSION);
compression_params.push_back(9);
bool result = false;
try
{
result = imwrite("alpha.png", mat, compression_params);
}
catch (const cv::Exception& ex)
{
fprintf(stderr, "Exception converting image to PNG format: %s\n", ex.what());
}
2020-07-02 04:50:09 +08:00
2017-12-31 19:13:13 +08:00
if (result)
printf("Saved PNG file with alpha data.\n");
else
printf("ERROR: Can't save PNG file.\n");
2020-07-02 04:50:09 +08:00
vector<Mat> imgs;
imgs.push_back(mat);
imgs.push_back(~mat);
imgs.push_back(mat(Rect(0, 0, mat.cols / 2, mat.rows / 2)));
imwrite("test.tiff", imgs);
printf("Multiple files saved in test.tiff\n");
2017-12-31 19:13:13 +08:00
return result ? 0 : 1;
}