构造高斯金字塔和拉普拉斯金字塔
1. 高斯金字塔和拉普拉斯金字塔简介
假设你的视觉算法只能识别大小恒定的物体,但物体在现实世界中随着空间的变换会表现出不同尺度。这时,高斯金字塔和拉普拉斯金字塔可以解决尺度变化问题。
高斯金字塔由一组不同大小的图像组成。通常在高斯金字塔的底层放置原始图像,当前层(顶层除外)的图像用高斯模板滤波,然后下采样后的图像放在当前层的上一层。拉普拉斯金字塔当前层的图像(与高斯金字塔的上一层对齐)等于高斯金字塔的上一层(底层除外)的上采样图像减去高斯金字塔的当前层图像。彩色图像为红绿蓝三通道值分别相减的结果。
2. 代码实现
import cv2
import numpy as np
from matplotlib import pyplot as plt
################################################################################
print 'Load Image'
imgFile = 'images/face.jpg'
# load an original image
img = cv2.imread(imgFile)
################################################################################
# color value range
cRange = 256
# convert color space from bgr to gray
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
imgGray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
################################################################################
# pyramid level
level = 5
# original image at the bottom of gaussian pyramid
higherResoGauss = img
plt.subplot(2,1 + level,1), plt.imshow(higherResoGauss), plt.title('Gaussian Level ' + '%d' % level), plt.xticks([]), plt.yticks([])
for l in range(level):
rows,cols,channels = higherResoGauss.shape
# delete last odd row of gaussian image
if rows % 2 == 1:
higherResoGauss = higherResoGauss[:rows - 1,:]
# delete last odd column of gaussian image
if cols % 2 == 1:
higherResoGauss = higherResoGauss[:,:cols - 1]
# gaussian image
lowerResoGauss = cv2.pyrDown(higherResoGauss)
# even rows and cols in up-sampled image
temp = cv2.pyrUp(lowerResoGauss)
print higherResoGauss.shape,temp.shape
# laplacian image
lowerResoLap = higherResoGauss - temp
# display gaussian and laplacian pyramid
plt.subplot(2,1 + level,l + 2), plt.imshow(lowerResoGauss), plt.title('Gaussian Level ' + '%d' % (level - l - 1)), plt.xticks([]), plt.yticks([])
plt.subplot(2,1 + level,1 + level + l + 2), plt.imshow(lowerResoLap), plt.title('Laplacian Level ' + '%d' % (level - l - 1)), plt.xticks([]), plt.yticks([])
higherResoGauss = lowerResoGauss
################################################################################
# display original image and gray image
plt.show()
################################################################################
print 'Goodbye!'
3. 实验结果
这里构建了6层高斯金字塔和5层拉普拉斯金字塔,上一行为高斯金字塔,下一行为拉普拉斯金字塔;从左往右的图像在金字塔上从下往上放置。显示的图像大小虽然相同,但像素大小不同。
结语
除了尺度问题,还需要考虑角度问题。所以,后面会针对实际问题,然后结合本节内容的思想并引入角度的变化来作扩展。