天天看點

利用opencv函數計算圖像的梯度幅度和梯度方向

沒有難點,就是為了友善使用記錄,自己實作的話比較麻煩,直接使用内置函數計算比較省心。

重點是這個函數:

C++:  void  gpu:: cartToPolar (const GpuMat&  x, const GpuMat&  y, GpuMat&  magnitude, GpuMat&  angle, bool  angleInDegrees=false, Stream& stream=Stream::Null() ) ¶

Parameters:
  • x – Source matrix containing real components ( CV_32FC1 ).
  • y – Source matrix containing imaginary components ( CV_32FC1 ).
  • magnitude – Destination matrix of float magnitudes ( CV_32FC1 ).
  • angle – Destionation matrix of angles ( CV_32FC1 ).
  • angleInDegress – Flag for angles that must be evaluated in degress.
  • stream – Stream for the asynchronous version.
#include<opencv2/opencv.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
int main()
{

	//*****注意:資料類型非常非常重要!!資料類型不一緻,程式不報錯,但是計算結果嚴重錯誤
	//如果是float類型就全是float,double類型就全是double

	float data[3][3]={2,4,3,
		7,5,6,
		4,-8,9};
	Mat mat=Mat(3,3,CV_32FC1,data);
	cout<<mat;
	cout<<endl<<"卷積運算"<<endl;
	Mat outmat1,outmat2;
	float k1[]={-1,0,1};  //水準方向的核
	float k2[3][1]={-1,0,1};  //垂直的核
	Mat Kore=Mat(1,3,CV_32FC1,k1);
	Mat Kore2=Mat(3,1,CV_32FC1,k2);
	filter2D(mat,outmat1,-1,Kore);    //水準卷積運算
	filter2D(mat,outmat2,-1,Kore2);  //垂直卷積運算

	cout<<outmat1<<endl;
	cout<<outmat2;
	Mat tidu;
	Mat jiaodu;
	cartToPolar(outmat1,outmat2,tidu,jiaodu,true);  //角度的結果在0-360之間
	cout<<"-----------------"<<endl;
	cout<<endl<<tidu;  //梯度幅度值圖
	cout<<endl<<jiaodu;   //角度圖
	

	waitKey(0);
	return 0;
}