函数画代码(python)
2026-03-01 14:07:43
发布于:浙江
import numpy as np
import matplotlib.pyplot as plt
import cv2
import tkinter as tk
from tkinter import simpledialog, scrolledtext, messagebox
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
# ===================== 核心配置(拉满256×256)=====================
KEEP_SIZE = 128 # 256×256的核心:中心128×2=256个函数(覆盖整幅图)
IMG_SIZE = 256 # 图像尺寸256×256,匹配256×256函数
FONT_SIZE = 7 # 缩小字体,适配6万+函数显示
WINDOW_SIZE = "1400x900" # 更大窗口,显示更舒适
# ===================== 图片加载+傅里叶函数提取(256×256超清版)=====================
def get_image_path():
"""弹出输入框获取图片路径"""
root = tk.Tk()
root.withdraw()
path = simpledialog.askstring(
title="输入图片路径",
prompt="粘贴图片路径(示例:r'C:\\Users\\Administrator\\Desktop\\xxx.jpg'):",
initialvalue=r"C:\Users\Administrator\Desktop\eff8f00a889027fad99a092f16b6c8a1.jpeg"
)
root.destroy()
return path if path else None
def load_image(image_path):
"""加载并预处理为256×256高清图"""
try:
img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
if img is None:
raise ValueError("图片读取失败!请检查路径/格式")
img = cv2.resize(img, (IMG_SIZE, IMG_SIZE), interpolation=cv2.INTER_CUBIC) # 高清缩放
return img
except Exception as e:
print(f"❌ 加载出错:{e}")
return None
def get_fft_functions_256(img):
"""
提取256×256=65536个函数公式(覆盖整幅图)
返回:函数列表 + 和原图完全一致的叠加图像
"""
rows, cols = img.shape
crow, ccol = rows//2, cols//2 # 256/2=128,中心位置
# 二维傅里叶变换(拆解为全部65536个基础函数)
fft2 = np.fft.fft2(img.astype(np.float32))
fft2_shift = np.fft.fftshift(fft2)
# 保留256×256全部函数
mask = np.ones((rows, cols), np.complex64) # 全1掩码,保留所有函数
fft_filtered = fft2_shift * mask
# 逆变换生成超清图像
fft_ishift = np.fft.ifftshift(fft_filtered)
img_recon = np.fft.ifft2(fft_ishift)
img_recon = np.abs(img_recon)
# 高清归一化,消除数值误差
img_recon = (img_recon - img_recon.min()) / (img_recon.max() - img_recon.min()) * 255
img_recon = img_recon.astype(np.uint8)
# 提取全部256×256=65536个函数公式
functions = []
func_idx = 1
# 遍历全部256×256个函数点(逐行逐列)
for m in range(rows):
for n in range(cols):
freq_x = n - ccol # x方向频率(-128~127)
freq_y = m - crow # y方向频率(-128~127)
amp = np.abs(fft2_shift[m,n]) / 10000 # 缩放振幅,公式更简洁
if freq_x == 0 and freq_y == 0:
# 直流分量(常数函数,决定图像整体亮度)
func_str = f"{func_idx}. 直流分量:f(x,y) = {amp:.6f}"
else:
# 二维正弦+余弦函数(绘制图像的基础单元)
func_str = (f"{func_idx}. f(x,y) = {amp:.6f}·cos(2π·{freq_x}x/{cols} + 2π·{freq_y}y/{rows}) "
f"+ {amp:.6f}·sin(2π·{freq_x}x/{cols} + 2π·{freq_y}y/{rows})")
functions.append(func_str)
func_idx += 1
# 进度提示(避免卡顿)
if func_idx % 10000 == 0:
print(f"🔄 已提取{func_idx}/65536个函数...")
return functions, img_recon, img
# ===================== 带滚动的超清UI(适配65536个函数)=====================
def create_ultra_ui(functions, img_original, img_recon, image_path):
"""创建超大滚动文本框的UI,显示65536个函数公式"""
# 1. 创建主窗口
root = tk.Tk()
root.title(f"256×256=65536个函数 - 超清图像生成 | {image_path}")
root.geometry(WINDOW_SIZE)
root.configure(bg="#f0f0f0")
# 2. 创建Matplotlib画布(显示超清图像对比)
fig = plt.figure(figsize=(10, 5), dpi=100) # 高DPI,图像更清晰
# 2.1 原始图像
ax1 = fig.add_subplot(121)
ax1.imshow(img_original, cmap='gray', vmin=0, vmax=255)
ax1.set_title('原始图像(256×256)', fontsize=14, fontweight='bold')
ax1.axis('off')
# 2.2 256×256函数叠加的超清图像(和原图一致)
ax2 = fig.add_subplot(122)
ax2.imshow(img_recon, cmap='gray', vmin=0, vmax=255)
ax2.set_title(f'256×256=65536个函数叠加图像(超清)', fontsize=14, fontweight='bold')
ax2.axis('off')
# 嵌入Tkinter窗口
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1, padx=10, pady=10)
# 3. 创建超大滚动文本框(显示65536个函数)
text_frame = tk.Frame(root, bg="#f0f0f0")
text_frame.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=1, padx=10, pady=5)
# 滚动条(双向滚动,更流畅)
scroll_y = tk.Scrollbar(text_frame, orient=tk.VERTICAL)
scroll_x = tk.Scrollbar(text_frame, orient=tk.HORIZONTAL)
scroll_y.pack(side=tk.RIGHT, fill=tk.Y)
scroll_x.pack(side=tk.BOTTOM, fill=tk.X)
# 超大数据滚动文本框(适配6万+函数)
func_text = scrolledtext.ScrolledText(
text_frame,
font=("Consolas", FONT_SIZE), # 等宽小字,适配大量文本
yscrollcommand=scroll_y.set,
xscrollcommand=scroll_x.set,
wrap=tk.NONE, # 不自动换行,公式完整显示
bg="black", # 黑底白字,看久了不累
fg="white"
)
func_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
scroll_y.config(command=func_text.yview)
scroll_x.config(command=func_text.xview)
# 4. 填充65536个函数公式(分批加载,避免卡顿)
func_text.insert(tk.END, f"📌 256×256=65536个函数(覆盖整幅图)\n")
func_text.insert(tk.END, f"📌 图片路径:{image_path}\n")
func_text.insert(tk.END, f"📌 叠加图像与原图1:1完全一致\n\n")
# 分批插入(每1000个一批,避免UI卡死)
batch_size = 1000
for i in range(0, len(functions), batch_size):
batch = functions[i:i+batch_size]
func_text.insert(tk.END, "\n".join(batch) + "\n")
root.update_idletasks() # 实时刷新UI
print(f"🔄 已加载{i+batch_size}/65536个函数公式...")
# 5. 保存按钮(导出65536个函数到文件)
def save_all_functions():
try:
with open("256x256_超清函数列表_65536个.txt", "w", encoding='utf-8') as f:
f.write(f"图片路径:{image_path}\n")
f.write(f"函数总数:256×256=65536个\n")
f.write(f"叠加效果:与原图1:1完全一致\n\n")
for func in functions:
f.write(func + "\n")
messagebox.showinfo("保存成功", "65536个函数公式已保存到:256x256_超清函数列表_65536个.txt")
except Exception as e:
messagebox.showerror("保存失败", f"错误:{e}")
save_btn = tk.Button(
root,
text="📥 导出65536个函数公式到TXT",
command=save_all_functions,
font=("微软雅黑", 11),
bg="#2196F3",
fg="white",
padx=20,
pady=5
)
save_btn.pack(side=tk.BOTTOM, pady=8)
# 运行主循环
root.mainloop()
# ===================== 主程序(256×256超清版)=====================
if __name__ == "__main__":
print("🚀 256×256超清模式启动 - 共65536个函数叠加...")
# 1. 获取路径+加载256×256高清图
IMAGE_PATH = get_image_path()
if not IMAGE_PATH:
print("❌ 未输入路径,程序退出")
exit()
img_original = load_image(IMAGE_PATH)
if img_original is None:
exit()
# 2. 提取256×256=65536个函数 + 生成超清图像
print("🔄 正在提取65536个函数公式(约10秒)...")
func_list, img_recon, img_original = get_fft_functions_256(img_original)
# 3. 创建超清UI,显示所有函数
print("✅ 函数提取完成!正在创建滚动UI...")
create_ultra_ui(func_list, img_original, img_recon, IMAGE_PATH)
print("🎉 程序运行完成!叠加图像与原图完全一致,65536个函数公式可滚动查看/导出")
以上就是函数画的所有代码。
提个醒:这个图片最好是正方形、黑白,不然会有点问题
这里空空如也














有帮助,赞一个