using namespace std;
int main()
{
cv::Mat gray = cv::imread("test.jpg", cv::IMREAD_GRAYSCALE);
if (gray.empty())
{
cout << "failed to read image" << endl;
return -1;
}
cv::namedWindow("src", cv::WINDOW_AUTOSIZE);
cv::imshow("src", gray);
cv::Mat matPadded;
const int optimalRows = cv::getOptimalDFTSize(gray.rows);
const int optimalCols = cv::getOptimalDFTSize(gray.cols);
cv::copyMakeBorder(gray, matPadded, 0, optimalRows - gray.rows, 0, optimalCols - gray.cols, cv::BORDER_CONSTANT, cv::Scalar::all(0));
cv::Mat matPaddedDouble;
matPadded.convertTo(matPaddedDouble, CV_64FC1);
cv::Mat dftResult;
cv::dft(matPaddedDouble, dftResult, cv::DFT_COMPLEX_OUTPUT);
if (dftResult.empty())
{
cout << "failed to dft" << endl;
return -1;
}
cv::Mat dftResultChannels[] = { cv::Mat::zeros(dftResult.size(), CV_64FC1), cv::Mat::zeros(dftResult.size(), CV_64FC1) };
cv::split(dftResult, dftResultChannels);
cv::Mat matMagnitude;
cv::magnitude(dftResultChannels[0], dftResultChannels[1], matMagnitude);
cv::imshow("raw magnitude", matMagnitude);
matMagnitude += cv::Scalar::all(1);
cv::log(matMagnitude, matMagnitude);
cv::imshow("log magnitude", matMagnitude);
cv::normalize(matMagnitude, matMagnitude, 0, 1, cv::NORM_MINMAX);
cv::imshow("normalized log magnitude", matMagnitude);
int rows = ((matMagnitude.rows & (2 - 1)) == 1) ? (matMagnitude.rows - 1) : matMagnitude.rows;
int cols = ((matMagnitude.cols & (2 - 1)) == 1) ? (matMagnitude.cols - 1) : matMagnitude.cols;
matMagnitude = matMagnitude(cv::Rect(0, 0, cols, rows));
int centerX = cols >> 1, centerY = rows >> 1;
cv::Mat topLeft(matMagnitude, cv::Rect(0, 0, centerX, centerY));
cv::Mat topRight(matMagnitude, cv::Rect(centerX, 0, centerX, centerY));
cv::Mat bottomLeft(matMagnitude, cv::Rect(0, centerY, centerX, centerY));
cv::Mat bottomRight(matMagnitude, cv::Rect(centerX, centerY, centerX, centerY));
cv::Mat tmp;
topLeft.copyTo(tmp), bottomRight.copyTo(topLeft), tmp.copyTo(bottomRight);
topRight.copyTo(tmp), bottomLeft.copyTo(topRight), tmp.copyTo(bottomLeft);
cv::imshow("centered magnitude", matMagnitude);
cv::waitKey(0);
return 0;
}