Python实现图像高斯金字塔的完整代码与解析

Cora
Cora
发布时间:2026-10-14| 4人浏览过
原创

本文详细介绍使用Python和OpenCV实现图像高斯金字塔的方法。通过自定义灰度转换与双线性插值函数,代码展示了从原图生成多级下采样图像的过程。包含完整的Python源码、关键算法解析及可视化输出示例,帮助开发者理解图像金字塔的构建原理与代码实现细节。

Python实现图像高斯金字塔的核心代码


import cv2
import numpy as np
import matplotlib.pyplot as plt

# Grayscale
def BGR2GRAY(img):
  # Grayscale
  gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0]
  return gray

# Bi-Linear interpolation
def bl_interpolate(img, ax=1., ay=1.):
  if len(img.shape) > 2:
    H, W, C = img.shape
  else:
    H, W = img.shape
    C = 1

  aH = int(ay * H)
  aW = int(ax * W)

  # get position of resized image
  y = np.arange(aH).repeat(aW).reshape(aW, -1)
  x = np.tile(np.arange(aW), (aH, 1))

  # get position of original position
  y = (y / ay)
  x = (x / ax)

  ix = np.floor(x).astype(np.int)
  iy = np.floor(y).astype(np.int)

  ix = np.minimum(ix, W-2)
  iy = np.minimum(iy, H-2)

  # get distance 
  dx = x - ix
  dy = y - iy

  if C > 1:
    dx = np.repeat(np.expand_dims(dx, axis=-1), C, axis=-1)
    dy = np.repeat(np.expand_dims(dy, axis=-1), C, axis=-1)

  # interpolation
  out = (1-dx) * (1-dy) * img[iy, ix] + dx * (1 - dy) * img[iy, ix+1] + (1 - dx) * dy * img[iy+1, ix] + dx * dy * img[iy+1, ix+1]

  out = np.clip(out, 0, 255)
  out = out.astype(np.uint8)

  return out

# make image pyramid
def make_pyramid(gray):
  # first element
  pyramid = [gray]
  # each scale
  for i in range(1, 6):
    # define scale
    a = 2. ** i

    # down scale
    p = bl_interpolate(gray, ax=1./a, ay=1. / a)

    # add pyramid list
    pyramid.append(p)
    
  return pyramid

# Read image
img = cv2.imread("../bird.png").astype(np.float)

gray = BGR2GRAY(img)

# pyramid
pyramid = make_pyramid(gray)

for i in range(6):
  cv2.imwrite("out_{}.jpg".format(2**i), pyramid[i].astype(np.uint8))
  plt.subplot(2, 3, i+1)
  plt.title('1/' + str((i+1)**2) )
  plt.imshow(pyramid[i], cmap='gray')
  plt.axis('off')
  plt.xticks(color="None")
  plt.yticks(color="None")

plt.show()

总结与参考资料

以上即为使用Python构建图像高斯金字塔的完整示例。如需获取更多关于Python图像处理及高斯金字塔应用的资料,建议查阅本站发布的其他相关技术文章。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。