看代码应该知道什么意思!第一次赋值做出图第二次像改变里面的值 为什么直接抛异常了?我是新手自己做得 没有老师!还请来位老师大能帮帮解惑谢谢
1 #include <iostream> 2 #include <opencv2/core/core.hpp> 3 #include <opencv2/highgui/highgui.hpp> 4 5 using namespace std; 6 using namespace cv; 7 8 Mat src; 9 Mat image; 10 string str = "./"; 11 12 /*创建alpha表,整体偏红色,左上角到右下角呈现从完全透明到完全不透明变化趋势*/ 13 void createAlphaMat(Mat &mat) 14 { 15 for (int i = 0; i < mat.rows; ++i) { 16 for (int j = 0; j < mat.cols; ++j) { 17 Vec4b& rgba = mat.at<Vec4b>(i, j); 18 rgba[0] = UCHAR_MAX; //r分量一直最大,所以整体偏红 19 rgba[1] = saturate_cast<uchar>((float(mat.cols - j)) / ((float)mat.cols) * UCHAR_MAX); 20 rgba[2] = saturate_cast<uchar>((float(mat.rows - i)) / ((float)mat.rows) * UCHAR_MAX); 21 rgba[3] = saturate_cast<uchar>(0.5 * (rgba[1] + rgba[2])); 22 } 23 } 24 } 25 26 int main() 27 { 28 29 /*采用自己设置的参数来保存图片*/ 30 Mat mat(480, 640, CV_8UC4); 31 createAlphaMat(mat); 32 vector<int> compression_params; 33 compression_params.push_back(IMWRITE_PNG_COMPRESSION); 34 compression_params.push_back(9); //png格式下,默认的参数为3. 35 try { 36 imwrite("alpha.png", mat, compression_params); 37 } 38 catch (runtime_error& ex) { 39 fprintf(stderr, "Exception converting image to PNG format: %s\n", ex.what()); 40 return 1; 41 for (int i = 0; i < mat.rows; ++i) { 42 for (int j = 0; j < mat.cols; ++j) { 43 mat.at<Vec4b>(i, j)[0] = 0; 44 mat.at<Vec4b>(i, j)[1] = 0; 45 mat.at<Vec4b>(i, j)[2] = 0; 46 } 47 } 48 } 49 imshow("as", mat); 50 if (waitKey(1) == 27){ 51 52 } 53 fprintf(stdout, "Saved PNG file with alpha data.\n"); 54 55 waitKey(0); 56 return 0; 57 }