求编写Windows环境下PNG灰度图逐像素对比处理代码
实现灰度图片逐像素取最大值的工具代码
前置准备
打开Windows命令提示符,输入以下命令安装所需依赖库:pip install pillow
代码实现
把下面的代码复制到记事本,保存为image_max_merge.py(保存时注意文件类型选「所有文件」,编码选UTF-8):
import tkinter as tk from tkinter import filedialog from PIL import Image # 隐藏tkinter的空白主窗口 root = tk.Tk() root.withdraw() # 选择第一张灰度PNG图片 print("请选择第一张灰度PNG图片") img_path1 = filedialog.askopenfilename(filetypes=[("PNG图片", "*.png")]) if not img_path1: print("未选择第一张图片,程序退出") exit() # 选择第二张灰度PNG图片 print("请选择第二张灰度PNG图片") img_path2 = filedialog.askopenfilename(filetypes=[("PNG图片", "*.png")]) if not img_path2: print("未选择第二张图片,程序退出") exit() # 打开图片并转为灰度模式 try: img1 = Image.open(img_path1).convert("L") img2 = Image.open(img_path2).convert("L") except Exception as e: print(f"打开图片出错:{e}") exit() # 检查两张图片尺寸是否一致 if img1.size != img2.size: print("两张图片尺寸不一致,无法处理") exit() width, height = img1.size # 创建空白灰度图用于保存结果 new_img = Image.new("L", (width, height)) # 逐像素对比取最大值 for y in range(height): for x in range(width): pixel1 = img1.getpixel((x, y)) pixel2 = img2.getpixel((x, y)) new_pixel = max(pixel1, pixel2) new_img.putpixel((x, y), new_pixel) # 保存处理后的图片 new_img.save("newfile.png") print("处理完成!结果已保存为newfile.png(和代码在同一文件夹)")
使用方法
- 双击运行
image_max_merge.py,按弹窗提示依次选择两张灰度PNG图片 - 程序会自动校验图片尺寸,一致则开始处理
- 处理完成后,在代码所在文件夹即可找到生成的
newfile.png
内容的提问来源于stack exchange,提问作者albert venter
相关产品推荐
相关产品推荐

