OpenCV 3.1 imwrite()函数写入异常问题解决方法
OpenCV 3.1 imwrite()函數(shù)寫入異常問題解決方法
最近配置了OpenCV3.1版本,按照2.x的習(xí)慣寫了一個保存圖片的代碼(測試證明該代碼在2.4.11下運(yùn)行正常),但是在使用imwrite()函數(shù)的時候出現(xiàn)了異常。 代碼如下:
#include <opencv2/imgproc/imgproc.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream>using namespace std; using namespace cv;int main() {Mat SrcImage = imread("1.jpg");imwrite("讀入的圖片.png", SrcImage);imshow("原圖", SrcImage);waitKey(0);return 0; }只是很簡單的讀入一個圖片然后再保存它。運(yùn)行后異常如下:
修改辦法: 1.是將debug模式修改為Release,代碼不用修改的情況下即可正常運(yùn)行。 2.將imwrite()函數(shù)寫入第三個參數(shù),我們查看imwrite()的定義可以看到一個官方給出的例子:
#include <opencv2/opencv.hpp>using namespace cv;using namespace std;void createAlphaMat(Mat &mat){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; // Bluebgra[1] = saturate_cast<uchar>((float (mat.cols - j)) / ((float)mat.cols) * UCHAR_MAX); // Greenbgra[2] = saturate_cast<uchar>((float (mat.rows - i)) / ((float)mat.rows) * UCHAR_MAX); // Redbgra[3] = saturate_cast<uchar>(0.5 * (bgra[1] + bgra[2])); // Alpha}}}int main(int argv, char **argc){// Create mat with alpha channelMat mat(480, 640, CV_8UC4);createAlphaMat(mat);vector<int> compression_params;compression_params.push_back(IMWRITE_PNG_COMPRESSION);compression_params.push_back(9);try {imwrite("alpha.png", mat, compression_params);}catch (cv::Exception& ex) {fprintf(stderr, "Exception converting image to PNG format: %s\n", ex.what());return 1;}fprintf(stdout, "Saved PNG file with alpha data.\n");return 0;}IMWRITE_PNG_COMPRESSION 為對于PNG格式的圖片,這個參數(shù)表示壓縮級別(CV_IMWRITE_PNG_COMPRESSION)從0到9。較高的值意味著更小的尺寸和更長的壓縮時間,而默認(rèn)值是3。 所以上述程序中選擇了壓縮級別為9。除此之外OpenCV還提供了很多種其他的保存格式,在轉(zhuǎn)到定義后的imgcodecs.hpp文件中都有很詳細(xì)的介紹。
所以 我們只需要簡單改寫代碼,即可解決異常問題。
#include <opencv2/imgproc/imgproc.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream>using namespace std; using namespace cv;int main() {Mat SrcImage = imread("1.jpg");vector<int> compression_params;compression_params.push_back(IMWRITE_PNG_COMPRESSION);compression_params.push_back(9);imwrite("讀入的圖片.png", SrcImage, compression_params);imshow("原圖", SrcImage);waitKey(0);return 0; }最后,用以上兩種辦法都解決了異常,但是異常產(chǎn)生的原因是什么,為什么這樣做就沒有異常了,尤其是params參數(shù)本身就帶默認(rèn)值。這個問題我也沒有弄明白,弄懂后在更新出來。
轉(zhuǎn)載自 https://cloud.tencent.com/developer/article/1010015
總結(jié)
以上是生活随笔為你收集整理的OpenCV 3.1 imwrite()函数写入异常问题解决方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【批处理】通过bat文件执行python
- 下一篇: Pytest装饰器@pytest.mar