imgcodecs_imwrite.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include <opencv2/imgcodecs.hpp>
  2. using namespace cv;
  3. using namespace std;
  4. static void paintAlphaMat(Mat &mat)
  5. {
  6. CV_Assert(mat.channels() == 4);
  7. for (int i = 0; i < mat.rows; ++i)
  8. {
  9. for (int j = 0; j < mat.cols; ++j)
  10. {
  11. Vec4b& bgra = mat.at<Vec4b>(i, j);
  12. bgra[0] = UCHAR_MAX; // Blue
  13. bgra[1] = saturate_cast<uchar>((float (mat.cols - j)) / ((float)mat.cols) * UCHAR_MAX); // Green
  14. bgra[2] = saturate_cast<uchar>((float (mat.rows - i)) / ((float)mat.rows) * UCHAR_MAX); // Red
  15. bgra[3] = saturate_cast<uchar>(0.5 * (bgra[1] + bgra[2])); // Alpha
  16. }
  17. }
  18. }
  19. int main()
  20. {
  21. Mat mat(480, 640, CV_8UC4); // Create a matrix with alpha channel
  22. paintAlphaMat(mat);
  23. vector<int> compression_params;
  24. compression_params.push_back(IMWRITE_PNG_COMPRESSION);
  25. compression_params.push_back(9);
  26. bool result = false;
  27. try
  28. {
  29. result = imwrite("alpha.png", mat, compression_params);
  30. }
  31. catch (const cv::Exception& ex)
  32. {
  33. fprintf(stderr, "Exception converting image to PNG format: %s\n", ex.what());
  34. }
  35. if (result)
  36. printf("Saved PNG file with alpha data.\n");
  37. else
  38. printf("ERROR: Can't save PNG file.\n");
  39. vector<Mat> imgs;
  40. imgs.push_back(mat);
  41. imgs.push_back(~mat);
  42. imgs.push_back(mat(Rect(0, 0, mat.cols / 2, mat.rows / 2)));
  43. imwrite("test.tiff", imgs);
  44. printf("Multiple files saved in test.tiff\n");
  45. return result ? 0 : 1;
  46. }