使用python3制作一个图片(格式png、jpg)消除指定颜色的工具,需求如下:
- 能输入一个图片绝对路径;
- 程序遍历所有像素点,并统计各个像素点颜色类型个数并打印出来给用户选择;
- 用户输入要消除的颜色类型,程序将所有该颜色类型的像素点替换为白色;
- 将处理后的图片保存到指定路径,并打印出处理后的图片路径。
python代码实现
from PIL import Image
import os
from collections import defaultdict
def analyze_image_colors(image_path):
"""分析图片中的颜色并统计各颜色出现次数"""
try:
img = Image.open(image_path)
color_counts = defaultdict(int)
# 获取图片的像素数据
pixels = img.getdata()
# 统计每种颜色的出现次数
for pixel in pixels:
# 对于带透明度的图片,只考虑RGB
if len(pixel) == 4:
color = pixel[:3]
else:
color = pixel
color_counts[color] += 1
return img, color_counts
except Exception as e:
print(f"无法打开图片: {e}")
return None, None
def replace_color(image, target_color):
"""将图片中的指定颜色替换为白色"""
if image is None:
return None
# 创建新图片,与原图相同模式
new_img = Image.new(image.mode, image.size)
pixels = list(image.getdata())
# 处理每个像素
new_pixels = []
for pixel in pixels:
# 处理带透明度的图片
if len(pixel) == 4:
color = pixel[:3]
alpha = pixel[3]
if color == target_color:
new_pixel = (255, 255, 255, alpha) # 替换为白色,保留透明度
else:
new_pixel = pixel
else:
if pixel == target_color:
new_pixel = (255, 255, 255) # 替换为白色
else:
new_pixel = pixel
new_pixels.append(new_pixel)
# 将处理后的像素数据放入新图片
new_img.putdata(new_pixels)
return new_img
def save_image(image, original_path, output_dir=None):
"""保存处理后的图片"""
if image is None:
return None
# 确定输出路径
if output_dir is None:
output_dir = os.path.dirname(original_path)
# 构造新文件名
basename = os.path.basename(original_path)
name, ext = os.path.splitext(basename)
new_name = f"{name}_processed{ext}"
output_path = os.path.join(output_dir, new_name)
# 确保目录存在
os.makedirs(output_dir, exist_ok=True)
# 保存图片
try:
image.save(output_path)
return output_path
except Exception as e:
print(f"保存图片失败: {e}")
return None
def color_tuple_from_str(color_str):
"""从字符串'(r, g, b)'转换为颜色元组"""
try:
# 去除括号和空格
color_str = color_str.strip()[1:-1]
parts = color_str.split(',')
return tuple(int(part.strip()) for part in parts)
except:
return None
def main():
print("=== 图片颜色消除工具 ===")
# 1. 输入图片路径
image_path = input("请输入图片的绝对路径: ").strip()
if not os.path.isfile(image_path):
print("错误: 文件不存在或路径无效")
return
# 2. 分析图片颜色
img, color_counts = analyze_image_colors(image_path)
if img is None:
return
print("\n图片中的颜色统计 (格式: (R, G, B): 出现次数):")
sorted_colors = sorted(color_counts.items(), key=lambda x: x[1], reverse=True)
for color, count in sorted_colors[:20]: # 只显示前20种最常见颜色
print(f"{color}: {count}次")
if len(sorted_colors) > 20:
print(f"... 还有 {len(sorted_colors)-20} 种其他颜色")
# 3. 用户选择要消除的颜色
while True:
color_str = input("\n请输入要消除的颜色 (格式: (R, G, B)): ").strip()
target_color = color_tuple_from_str(color_str)
if target_color is None or len(target_color) != 3:
print("错误: 颜色格式不正确,请使用 (R, G, B) 格式")
continue
if target_color not in color_counts:
print("警告: 该颜色不在图片中,请重新输入")
continue
break
# 4. 替换颜色并保存
print("\n正在处理图片...")
processed_img = replace_color(img, target_color)
output_dir = input("请输入保存目录 (留空则保存到原图目录): ").strip()
if not output_dir:
output_dir = None
output_path = save_image(processed_img, image_path, output_dir)
if output_path:
print(f"\n处理完成! 图片已保存到: {output_path}")
else:
print("\n处理过程中出现错误")
if __name__ == "__main__":
main()
以上为最初版本v1.0,后续逐步推出可视化操作版本,敬请期待。