1. 程式人生 > >Opencv計算影象的梯度

Opencv計算影象的梯度

#include "stdafx.h"
#include <opencv2/opencv.hpp>
#include <iostream>
#include <fstream>
#include <opencv2/core/core.hpp>   
#include<opencv2/highgui/highgui.hpp> 
#include <opencv.hpp>

using namespace cv;
using namespace std;

namespace EnerageGradient
{
	void GetKernel(int* &kernel, int wid)//核函式
	{
		for (size_t i = 0; i < wid*wid; i++)
		{
			kernel[i] = -1;
		}
		kernel[wid*wid / 2 ] = wid*wid - 1;
	}

/*--------------------------------------------
計算影象梯度
input:
	img 輸入影象
	wid 求取梯度的窗體大小
out:
    傳出影象
--------------------------------------------*/
	cv::Mat GetGradient(Mat &img,int wid)
	{
		Mat imgGradient(img.size().height,img.size().width,CV_8UC1);
		imgGradient = 0;
		int length = wid*wid;
		int *kernel = new int[length];
		memset(kernel, 0, length);
		GetKernel(kernel,wid);
		for (int i = wid/2; i < img.size().height-wid/2;i++)
		{
			uchar *imgG = imgGradient.ptr<uchar>(i);
			for (int j = wid/2; j < img.size().width-wid/2;j++)
			{
				int gradient_ij = 0;
				for (int k  = 0; k < wid; k++)
				{
					uchar *img0 = img.ptr<uchar>(i-wid/2+k);
					for (int m = 0; m < wid;m++)
					{
						int temp = kernel[k*wid + m];
						gradient_ij += img0[j-wid/2+m] *temp ;
					}
				}
				imgG[j] = abs(gradient_ij) ;
			}
		}
		delete[] kernel;
		return imgGradient;
	}
}