使用Python与Numpy构建2D Gaussian函数的可视化问题求助
问题:2D高斯函数建模与绘图不符合预期
我尝试用Python+Numpy建模2D高斯函数,代码如下:
import numpy as np def gauss_2d(x, y, amp, x0, y0, sigma_x, sigma_y, theta): a_gauss_2d = ((np.cos(theta)**2) / (2*sigma_x**2)) + ((np.sin(theta)**2) / (2*sigma_y**2)) b_gauss_2d = ((np.sin(2*theta)) / (2*sigma_x**2)) - ((np.sin(2*theta)) / (2*sigma_y**2)) c_gauss_2d = ((np.sin(theta)**2) / (2*sigma_x**2)) - ((np.cos(theta)**2) / (2*sigma_y**2)) term_1 = -1 * a_gauss_2d * ((x-x0) ** 2) term_2 = -1 * b_gauss_2d * (x-x0) * (y-y0) term_3 = -1 * c_gauss_2d * ((y-y0) ** 2) return amp* np.exp(term_1 + term_2 + term_3) x_arr = np.linspace(1, 1000, 10000) xx, yy = np.meshgrid(x_arr, x_arr) theta_deg = 90 theta_rad = theta_deg * np.pi/180 z_data = gauss_2d(xx, yy, 1, 55, 55, 20, 20, theta_rad) import matplotlib.pyplot as plt plt.contour(xx, yy, z_data, 50, cmap='winter') plt.xscale('log') plt.yscale('log') plt.colorbar() plt.show()
当前生成的轮廓图:
预期的2D高斯效果:
需要协助解决该问题。
问题分析与修正
核心问题点
- 高斯函数公式错误:
c_gauss_2d的符号及b_gauss_2d的系数不符合标准2D旋转高斯公式,导致形态扭曲。 - 坐标轴缩放不当:使用对数刻度压缩了中心区域,使得高斯形态无法正常展示,预期图为线性刻度效果。
- 网格范围不合理:x轴范围1-1000过大,高斯中心(55,55)在视图中占比极小,无法清晰呈现轮廓。
修正后的代码
import numpy as np import matplotlib.pyplot as plt def gauss_2d(x, y, amp, x0, y0, sigma_x, sigma_y, theta): # 修正标准2D旋转高斯的二次项参数 a = (np.cos(theta)**2)/(2*sigma_x**2) + (np.sin(theta)**2)/(2*sigma_y**2) b = (np.sin(2*theta))/(4*sigma_x**2) - (np.sin(2*theta))/(4*sigma_y**2) c = (np.sin(theta)**2)/(2*sigma_x**2) + (np.cos(theta)**2)/(2*sigma_y**2) # 匹配二次型ax² + 2bxy + cy²的结构 term1 = -a * (x - x0)**2 term2 = -2 * b * (x - x0) * (y - y0) term3 = -c * (y - y0)**2 return amp * np.exp(term1 + term2 + term3) # 缩小网格范围,聚焦高斯中心区域 x_arr = np.linspace(0, 110, 200) xx, yy = np.meshgrid(x_arr, x_arr) theta_deg = 90 theta_rad = np.deg2rad(theta_deg) z_data = gauss_2d(xx, yy, 1, 55, 55, 20, 20, theta_rad) # 使用线性刻度,匹配预期图展示方式 plt.contour(xx, yy, z_data, 50, cmap='winter') plt.colorbar() plt.show()
修正说明
- 公式修正:标准2D旋转高斯的二次型为 $ax^2 + 2bxy + cy^2$,原代码中
c项符号错误,b项系数和交叉项的系数不匹配,导致高斯形态变形。 - 坐标轴调整:移除对数刻度,改用线性刻度,同时将网格范围缩小至0-110,让高斯中心处于视图中心,完整展示轮廓。
- 代码优化:用
np.deg2rad()替代手动角度转换,代码更简洁规范。
内容的提问来源于stack exchange,提问作者Iceman_R1331
相关产品推荐
相关产品推荐

