opencv-034-图像锐化

知识点

图像卷积的主要有三功能分别是图像的模糊/去噪、图像梯度/边缘发现、图像锐化/增强,前面的两个功能我们以前通过相关知识点的分享加以了解,学习了相关API的使用。图像锐化的本质是图像拉普拉斯滤波加原图权重像素叠加的输出 :

1
2
3
-1   -1   -1
-1 C -1
-1 -1 -1
  • 当C值大于8时候表示图像锐化、越接近8表示锐化效果越好

  • 当C值等于8时候图像的高通滤波

  • 当C值越大,图像锐化效果在减弱、中心像素的作用在提升

代码(c++,python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

/*
* 图像锐化
*/
int main() {
Mat src = imread("../images/test.png");
if (src.empty()) {
cout << "could not load image.." << endl;
}
imshow("input", src);

Mat sharpen_op = (Mat_<char>(3,3) << -1, -1, -1,
-1, 9, -1,
-1, -1, -1);

// Mat sharpen_op1 = (Mat_<char>(3,3) << 0, -1, 0,
// -1, 9, -1,
// 0, -1, 0);

Mat dst;
filter2D(src, dst, CV_32F, sharpen_op);
convertScaleAbs(dst, dst);

imshow("sharpen", dst);

waitKey(0);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import cv2 as cv
import numpy as np

src = cv.imread("D:/images/test.jpg")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)

# sharpen_op = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]], dtype=np.float32)
sharpen_op = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], dtype=np.float32)
sharpen_image = cv.filter2D(src, cv.CV_32F, sharpen_op)
sharpen_image = cv.convertScaleAbs(sharpen_image)
cv.imshow("sharpen_image", sharpen_image)

h, w = src.shape[:2]
result = np.zeros([h, w*2, 3], dtype=src.dtype)
result[0:h,0:w,:] = src
result[0:h,w:2*w,:] = sharpen_image
cv.putText(result, "original image", (10, 30), cv.FONT_ITALIC, 1.0, (0, 0, 255), 2)
cv.putText(result, "sharpen image", (w+10, 30), cv.FONT_ITALIC, 1.0, (0, 0, 255), 2)
cv.imshow("sharpen_image", result)
cv.imwrite("D:/result.png", result)

cv.waitKey(0)
cv.destroyAllWindows()

结果

代码地址

github