今天学习使用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);
再次查看
终于正确,正确,正确了。