Quote :
It is indeed a well-known result in image processing that if you subtract its Laplacian from an image, the image edges are amplified giving a sharper image. [From OpenCV 2 Computer Vision Application Programming Cookbook]
- 对于求一个锐化后的像素点(sharpened_pixel),这个基于拉普拉斯算子的简单算法主要是遍历图像中的像素点,根据领域像素确定其锐化后的值
- 计算公式:sharpened_pixel = 5 * current – left – right – up – down ; [见Code1]
- 当一个运算是通过领域像素进行的时候,我们通常用一个矩阵来表示这种运算关系,也就是我们经常所说的 核 (Kernel) 。那么上面的 锐化滤波器 (Sharpening Filter) 就可以用这个矩阵表示为它的核:
-1 | ||
-1 | 5 | -1 |
-1 |
- 因为 滤波 在图像处理中是一个非常普通且常用的操作,所以OpenCV里面已经定义了一个特殊的函数用来执行这个操作。要使用它的话只需要定义一个 核 ,然后作为参数传递就行了。[见Code2]
Code 1 :
/*
Author : Ggicci
Date : 2012.07.19
File : sharp.h
*/
#pragma once#include <opencv\cv.h>
using namespace cv;namespace ggicci
{void sharpen(const Mat& img, Mat& result);}/*
Author : Ggicci
Date : 2012.07.19
File : sharp.cpp
*/
#include "sharp.h"void ggicci::sharpen(const Mat& img, Mat& result){result.create(img.size(), img.type());//处理边界内部的像素点, 图像最外围的像素点应该额外处理
for (int row = 1; row < img.rows-1; row++){//前一行像素点
const uchar* previous = img.ptr<const uchar>(row-1);//待处理的当前行
const uchar* current = img.ptr<const uchar>(row);//下一行
const uchar* next = img.ptr<const uchar>(row+1);uchar *output = result.ptr<uchar>(row);int ch = img.channels();
int starts = ch;
int ends = (img.cols - 1) * ch;
for (int col = starts; col < ends; col++){//输出图像的遍历指针与当前行的指针同步递增, 以每行的每一个像素点的每一个通道值为一个递增量, 因为要考虑到图像的通道数
*output++ = saturate_cast<uchar>(5 * current[col] - current[col-ch] - current[col+ch] - previous[col] - next[col]);}} //end loop
//处理边界, 外围像素点设为 0
result.row(0).setTo(Scalar::all(0));result.row(result.rows-1).setTo(Scalar::all(0));result.col(0).setTo(Scalar::all(0));result.col(result.cols-1).setTo(Scalar::all(0));}/*
Author : Ggicci
Date : 2012.07.19
File : main.cpp
*/
#include <opencv\highgui.h>
#pragma comment(lib, "opencv_core231d.lib")#pragma comment(lib, "opencv_highgui231d.lib")#pragma comment(lib, "opencv_imgproc231d.lib")using namespace cv;#include "sharp.h"int main()
{Mat lena = imread("lena.jpg");
Mat sharpenedLena;ggicci::sharpen(lena, sharpenedLena);imshow("lena", lena);
imshow("sharpened lena", sharpenedLena);
cvWaitKey();return 0;
}
Output 1 :
Code 2 :
1: int main()2: {
3: Mat lena = imread("lena.jpg");4: Mat sharpenedLena;
5: Mat kernel = (Mat_<float>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);6: cv::filter2D(lena, sharpenedLena, lena.depth(), kernel);
7:
8: imshow("lena", lena);9: imshow("sharpened lena", sharpenedLena);10: cvWaitKey();
11: return 0;12: }
Output 2 :