# 导入必要的库
import os
from PIL import Image
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap, Normalize
import numpy as np
import pandas as pd
import seaborn as sns
from scipy.ndimage import gaussian_filter
def smooth_data(data, sigma=3):
# 使用 Gaussian 滤波进行数据平滑处理
smoothed_data = gaussian_filter(data, sigma=sigma)
return smoothed_data
# 设置全局字体
plt.rcParams['font.family'] = 'Arial' # 请替换 ' Arial ' 为你希望使用的字体
plt.rcParams['font.size'] = 10 # 设置字体大小
# 获取当前路径下的所有图像文件
image_files = [file for file in os.listdir() if file.lower().endswith(('.png', '.jpg', '.jpeg', '.tif'))]
for image_file in image_files:
# 读取图像
image_path = os.path.join(os.getcwd(), image_file)
image = Image.open(image_path)
# 将图像转换为灰度图
gray_image = image.convert("L")
# 将灰度图转换为NumPy数组
data = np.array(gray_image)
# 对数据进行平滑处理
smoothed_data = smooth_data(data)
# 将平滑后的数据转换为长格式
df = pd.DataFrame(smoothed_data, columns=np.arange(data.shape[1])).stack().reset_index()
df.columns = ["X", "Y", "Z"]
# 将旧的列名转换为数值
df['X'] = pd.Categorical(df['X'])
df['X'] = df['X'].cat.codes
# 创建图形
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
#自定义颜色映射
colors = sns.color_palette("icefire", 256) # 请替换 ' icefire ' 为你希望使用的颜色映射
fire_cmap = ListedColormap(colors)
# 设置颜色映射范围为 0 到 100
norm = Normalize(vmin=0, vmax=100)
surf = ax.plot_trisurf(df['Y'], df['X'], df['Z'], cmap=fire_cmap, norm=norm, linewidth=0.6)
# 将结果保存为图像文件
result_image_path = f"result_{os.path.splitext(image_file)[0]}.png"
plt.savefig(result_image_path, bbox_inches='tight', dpi=300)
https://www.practicalpythonfordatascience.com/ap_seaborn_palette
pip install pillow matplotlib seaborn numpy scipy
如果您喜欢我们的文章,欢迎关注