美文网首页
OpenCV Python实现图像金字塔

OpenCV Python实现图像金字塔

作者: 学而时习之_不亦说乎 | 来源:发表于2018-03-30 05:26 被阅读404次

    图像金字塔一文中,已经详细介绍了图像金字塔的MATLAB实现,这里贴上OpenCV Python的实现以做补充。在OpenCV中,主要使用cv2.pyrDown和cv2.pyrUp两个函数,在没有指定输出图像的大小的情况下,下采样的图像尺寸会进行四舍五入。比如,189x189的图像会亚采样为95x95大小。为了保证在拉普拉斯金字塔和图像重建过程中的图像大小一致,下面的函数限制了下采样、上采样的输出图像大小(dstsize参数)。

    import cv2
    import numpy as np
    
    def gaussian_pyr(img,lev):
        img = img.astype(np.float)
        g_pyr = [img]
        cur_g = img;
        for index in range(lev):
            print(index)
            cur_g = cv2.pyrDown(cur_g)
            g_pyr.append(cur_g)
        return g_pyr
    
    
    def laplacian_pyr(img,lev):
        img = img.astype(np.float)
        g_pyr = gaussian_pyr(img,lev)
        l_pyr = []
        for index in range(lev):
            cur_g = g_pyr[index]
            cur_w,cur_h = np.shape(cur_g)
            next_g = cv2.pyrUp(g_pyr[index+1],dstsize=(cur_h,cur_w))
            cur_l = cv2.subtract(cur_g,next_g)
            l_pyr.append(cur_l)
        l_pyr.append(g_pyr[-1])
        return l_pyr
    
    def lpyr_recons(l_pyr):
        lev = len(l_pyr)
        cur_l = l_pyr[-1]
        for index in range(lev-2,-1,-1):
            #print(index)
            next_w,next_h = np.shape(l_pyr[index])
            cur_l = cv2.pyrUp(cur_l,dstsize=(next_h,next_w))
            next_l = l_pyr[index]
            cur_l = cur_l + next_l
        return cur_l
    

    对上面函数的测试:

    #from Uti.pyr import *
    #from Uti.utis import *
    import imageio
    import matplotlib.pyplot as plt
    img = imageio.imread('LENA.JPG')
    img = luminance(img)
    
    m = gaussian_pyr(img,5)
    for i in range(len(m)):
        plt.imshow(m[i],cmap='gray')
        plt.show()
    
    
    
    g = laplacian_pyr(img,5)
    for i in range(len(g)):
        plt.imshow(g[i],cmap='gray')
        plt.show()
    
    t = lpyr_recons(g)
    plt.imshow(t,cmap='gray')
    plt.show()
    

    相关文章

      网友评论

          本文标题:OpenCV Python实现图像金字塔

          本文链接:https://www.haomeiwen.com/subject/yikbcftx.html