Opencv--图像锐化处理

时间:2021-05-29 06:16:24

图像锐化处理(两种方法 1.过滤函数,自定义核 2. 直接处理当前像素点与邻近像素点关系)

// Sharpen.cpp : Defines the entry point for the console application.
/*-----CODE FOR FUN---------------
-------CREATED BY Dream_Whui------
-------2015-3-9-------------------------*/
//锐化处理,采用两种方法,1.手动编写处理相邻像素键的关系 2.核函数

#include "stdafx.h"
#include <iostream>
#include<opencv2\opencv.hpp>
using namespace cv;
using namespace std;

void Sharpen(const Mat &image, Mat &result)
{
result.create( image.size(), image.type() );
for(int j=1; j<image.rows-1; j++)
{
const uchar* previous = image.ptr<const uchar>(j-1);
const uchar* current = image.ptr<const uchar>(j);
const uchar* next = image.ptr<const uchar>(j+1);

uchar * output = result.ptr<uchar>(j);
for(int i=1; i<(image.cols-1); i++)
{
output[i*3] = saturate_cast<uchar>(5*current[i*3] - current[(i-1)*3] - current[(i+1)*3] - previous[i*3] - next[i*3]);
output[i*3+1] = saturate_cast<uchar>(5*current[i*3+1] - current[(i-1)*3+1] - current[(i+1)*3+1] - previous[i*3+1] - next[i*3+1]);
output[i*3+2] = saturate_cast<uchar>(5*current[i*3+2] - current[(i-1)*3+2] - current[(i+1)*3+2] - previous[i*3+2] - next[i*3+2]);
}
}
result.row(0).setTo(Scalar(0,0,0));
result.row(result.rows-1).setTo(Scalar(0,0,0));
result.col(0).setTo(Scalar(0,0,0));
result.col(result.cols-1).setTo(Scalar(0,0,0));
}

void SharpenKernel(const Mat &image, Mat &result)
{
Mat kernel(3,3,CV_32F,Scalar(0));
kernel.at<float>(1,1) = 5;
kernel.at<float>(0,1) = -1;
kernel.at<float>(2,1) = -1;
kernel.at<float>(1,0) = -1;
kernel.at<float>(1,2) = -1;
filter2D(image,result,image.depth(),kernel);
result.row(0).setTo(Scalar(0,0,0));
result.row(result.rows-1).setTo(Scalar(0,0,0));
result.col(0).setTo(Scalar(0,0,0));
result.col(result.cols-1).setTo(Scalar(0,0,0));
}

int _tmain(int argc, _TCHAR* argv[])
{
Mat image = imread("pic.jpg");
Mat result, result1;

Sharpen(image,result);
SharpenKernel(image,result1);

namedWindow("image");
imshow("image",image);

namedWindow("image_process");
imshow("image_process",result);

namedWindow("image_process_ker");
imshow("image_process_ker",result1);
waitKey();
return 0;
}