OpenCV_图像增强

自定义模板,调用,实现图像增强

这里的模板即是指核函数,也称掩码。本文主要是实现调用自定义掩码,实现图片增强。理论部分就不介绍了,直接上代码。

输入图片为:


增强后的效果图为:



代码如下:

#include "stdafx.h"
#include <opencv2/opencv.hpp>
#include <string>
#include <iostream>

using namespace cv;
using namespace std;

void Enthance(const Mat& srcImg,Mat& outImg);

int main()
{
	string imgPath = "C:\\Users\\Lily\\Desktop\\临时\\plate\\1.jpg";

	Mat inputImg = imread(imgPath,1);

	imshow("input",inputImg);
	waitKey(10);

	Mat resultImg;
	
	Enthance(inputImg,resultImg);

	imshow("outImg",resultImg);
	waitKey(0);


}

//************************************
// Method:    Sharpen
// FullName:  Sharpen
// Access:    采用模板对图像进行增强,模板为
// 0   -1    0
// -1   5    -1
// 0     -1    0
// Returns:   void
// Qualifier:
// Parameter: const Mat & srcImg
// Parameter: Mat & outImg
//************************************
void Enthance(const Mat& srcImg,Mat& outImg)
{
	CV_Assert(srcImg.depth() == CV_8U);  // 仅接受uchar图像

	outImg.create(srcImg.size(),srcImg.type()); //创建一个与输入同样大小和类型的输出图像
	const int nChannels = srcImg.channels();

	for(int j = 1 ; j < srcImg.rows-1; ++j)
	{
		const uchar* pre = srcImg.ptr<uchar>(j - 1); //获取每一行像素的指针
		const uchar* current  = srcImg.ptr<uchar>(j    );
		const uchar* next     = srcImg.ptr<uchar>(j + 1);

		uchar* output = outImg.ptr<uchar>(j); //指针存储计算结果存储位移,每次循环都对输出指针进行递增

		for(int i= nChannels;i < nChannels*(srcImg.cols-1); ++i)
		{
			*output++ = saturate_cast<uchar>(5*current[i]
			-current[i-nChannels] - current[i+nChannels] - pre[i] - next[i]);
		}
	}

	outImg.row(0).setTo(Scalar(0));  //不对图像的边界实施模板,将边界置零
	outImg.row(outImg.rows-1).setTo(Scalar(0));
	outImg.col(0).setTo(Scalar(0));
	outImg.col(outImg.cols-1).setTo(Scalar(0));
}

opencv内部也封装了滤波器,也可以直接调用滤波器实现这个功能,代码如下:

#include "stdafx.h"
#include <opencv2/opencv.hpp>
#include <string>
#include <iostream>

using namespace cv;
using namespace std;


int main()
{
	string imgPath = "C:\\Users\\Lily\\Desktop\\临时\\plate\\1.jpg";

	Mat inputImg = imread(imgPath,1);

	imshow("input",inputImg);
	waitKey(10);

	Mat resultImg;
	
	Mat kern = (Mat_<char>(3,3)<<0, -1, 0,
		                         -1, 5, -1,
		                         0,  -1, 0);
	filter2D(inputImg,resultImg,inputImg.depth(),kern);

	imshow("outImg",resultImg);
	waitKey(0);


}


你可能感兴趣的:(图像处理)