opencv-038-拉普拉斯金字塔

知识点

对输入图像实现金字塔的reduce操作就会生成不同分辨率的图像、对这些图像进行金字塔expand操作,然后使用reduce减去expand之后的结果就会得到图像拉普拉斯金字塔图像。
举例如下:
输入图像G(0)
金字塔reduce操作生成 G(1), G(2), G(3)
拉普拉斯金字塔:
L0 = G(0)-expand(G(1))
L1 = G(1)-expand(G(2))
L2 = G(2)–expand(G(3))
G(0)减去expand(G(1))得到的结果就是两次高斯模糊输出的不同,所以L0称为DOG(高斯不同)、它约等于LOG所以又称为拉普拉斯金字塔。所以要求的图像的拉普拉斯金字塔,首先要进行金字塔的reduce操作,然后在通过expand操作,最后相减得到拉普拉斯金字塔图像。

代码(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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

void pyramid_up(Mat &image, vector<Mat> &pyramid_images, int level);

void laplaian_demo(vector<Mat> &pyramid_images, Mat &image);

/*
* 拉普拉斯金字塔
*/
int main() {
Mat src = imread("../images/test1.jpg");
if (src.empty()) {
cout << "could not load image.." << endl;
}
imshow("input", src);

vector<Mat> p_images;
pyramid_up(src, p_images, 2);
laplaian_demo(p_images, src);

waitKey(0);
return 0;
}

void laplaian_demo(vector<Mat> &pyramid_images, Mat &image) {
for (int i = pyramid_images.size() - 1; i > -1; --i) {
Mat dst;
if (i - 1 < 0) {
pyrUp(pyramid_images[i], dst, image.size());
subtract(image, dst, dst);
dst = dst + Scalar(127, 127, 127);# 调亮度, 实际中不能这么用
imshow(format("laplaian_layer_%d", i), dst);
} else {
pyrUp(pyramid_images[i], dst, pyramid_images[i-1].size());
subtract(pyramid_images[i - 1], dst, dst);
dst = dst + Scalar(127, 127, 127);
imshow(format("laplaian_layer_%d", i), dst);
}
}
}

void pyramid_up(Mat &image, vector<Mat> &pyramid_images, int level) {
Mat temp = image.clone();
Mat dst;
for (int i = 0; i < level; ++i) {
pyrDown(temp, dst);
//imshow(format("pyramid_up_%d", i), dst);
temp = dst.clone();
pyramid_images.push_back(temp);
}
}
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
34
35
36
37
38
39
import cv2 as cv
import numpy as np


def laplaian_demo(pyramid_images):
level = len(pyramid_images)
for i in range(level-1, -1, -1):
if (i-1) < 0:
h, w = src.shape[:2]
expand = cv.pyrUp(pyramid_images[i], dstsize=(w, h))
lpls = cv.subtract(src, expand) + 127
cv.imshow("lpls_" + str(i), lpls)
else:
h, w = pyramid_images[i-1].shape[:2]
expand = cv.pyrUp(pyramid_images[i], dstsize=(w, h))
lpls = cv.subtract(pyramid_images[i-1], expand) + 127
cv.imshow("lpls_"+str(i), lpls)


def pyramid_up(image, level=3):
temp = image.copy()
# cv.imshow("input", image)
pyramid_images = []
for i in range(level):
dst = cv.pyrDown(temp)
pyramid_images.append(dst)
# cv.imshow("pyramid_up_" + str(i), dst)
temp = dst.copy()
return pyramid_images


src = cv.imread("D:/images/master.jpg")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)
# pyramid_up(src)
laplaian_demo(pyramid_up(src))

cv.waitKey(0)
cv.destroyAllWindows()

结果

代码地址

github