【opencv圖片保存出錯問題】

今天學習使用opencv的過程中,遇到一個奇怪問題,圖片處理後直接用imshow顯示可以,保存後,用圖片查看器查看,卻是一張純黑色的圖。

程序源代碼如下:

/***********************************************************
Function:        dft_precess
Description :    圖片的離散傅里葉變化
Called By :
Input :
Return :
************************************************************/
int dft_precess(string src_dir, string dst_dir, bool test_sign)
{
	Mat src, dst;
	/// 裝載圖像
	src = imread(src_dir, 1);
	if (!src.data)
	{
		return -1;
		cout << "error exit." << endl;
	}
	cvtColor(src, src, CV_RGB2GRAY);
	Mat padded;                            //expand input image to optimal size
	int m = getOptimalDFTSize(src.rows);
	int n = getOptimalDFTSize(src.cols); // on the border add zero values
	copyMakeBorder(src, padded, 0, m - src.rows, 0, n - src.cols, BORDER_CONSTANT, Scalar::all(0));
	
	vector<Mat> planes(2);
	
	planes[0] = Mat_<float>(padded);
	
	planes[1]= Mat::zeros(m, n, CV_32FC(1));

	
	Mat complexI;
	
	merge(planes, complexI);         // Add to the expanded another plane with zeros
	
	dft(complexI, complexI);            // this way the result may fit in the source matrix

	// compute the magnitude and switch to logarithmic scale
	// => log(1 + sqrt(Re(DFT(I))^2 + Im(DFT(I))^2))
	split(complexI, planes);                   // planes[0] = Re(DFT(I), planes[1] = Im(DFT(I))
	magnitude(planes[0], planes[1], planes[0]);// planes[0] = magnitude  
	Mat magI = planes[0];

	magI += Scalar::all(1);                    // switch to logarithmic scale
	log(magI, magI);

	// crop the spectrum, if it has an odd number of rows or columns
	magI = magI(Rect(0, 0, magI.cols & -2, magI.rows & -2));

	// rearrange the quadrants of Fourier image  so that the origin is at the image center        
	int cx = magI.cols / 2;
	int cy = magI.rows / 2;

	Mat q0(magI, Rect(0, 0, cx, cy));   // Top-Left - Create a ROI per quadrant 
	Mat q1(magI, Rect(cx, 0, cx, cy));  // Top-Right
	Mat q2(magI, Rect(0, cy, cx, cy));  // Bottom-Left
	Mat q3(magI, Rect(cx, cy, cx, cy)); // Bottom-Right

	Mat tmp;                           // swap quadrants (Top-Left with Bottom-Right)
	q0.copyTo(tmp);
	q3.copyTo(q0);
	tmp.copyTo(q3);

	q1.copyTo(tmp);                    // swap quadrant (Top-Right with Bottom-Left)
	q2.copyTo(q1);
	tmp.copyTo(q2);
	normalize(magI, dst, 0, 1, CV_MINMAX); // Transform the matrix with float values into a 
	// viewable image form (float between values 0 and 1)
	//dst.convertTo(dst, CV_8UC1, 255, 0);
	if (test_sign)
	{
		/// 創建顯示窗口
		namedWindow("test", CV_WINDOW_AUTOSIZE);
		imshow("test", dst);
		waitKey(0);
	}
	else
	{
		imwrite(dst_dir, dst);
	}
	return 0;
}



運行程序測試一下,直接查看一張灰度圖的dft的結果如下:



非測試狀態,處理完直接保存,然後直接用圖片查看器查看圖片的狀態爲一張純黑色的圖。


問題原因

dft變化後歸一化到了[0-1],即數值小,故顯示的黑色,只需要將數值從[0-1]放縮到[0-255]即可。


解決方法

在歸一化的後面加一句代碼,將圖片type從float轉化爲unsigned格式,同時放大255倍,然後再保存。

dst.convertTo(dst, CV_8UC1, 255, 0);


再次查看



  終於正確,正確,正確了。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章