251 lines
		
	
	
		
			8.4 KiB
		
	
	
	
		
			Python
		
	
	
	
			
		
		
	
	
			251 lines
		
	
	
		
			8.4 KiB
		
	
	
	
		
			Python
		
	
	
	
| #!/usr/bin/env python3
 | ||
| """
 | ||
| 胡汉三千年项目 - 图像转换工具
 | ||
| 支持 PPM -> PNG/JPG/SVG 转换
 | ||
| """
 | ||
| 
 | ||
| import os
 | ||
| import sys
 | ||
| from pathlib import Path
 | ||
| import argparse
 | ||
| 
 | ||
| def install_requirements():
 | ||
|     """安装必要的依赖包"""
 | ||
|     import subprocess
 | ||
|     
 | ||
|     packages = [
 | ||
|         'Pillow>=10.0.0',  # PIL的现代版本
 | ||
|         'opencv-python>=4.8.0',  # OpenCV
 | ||
|         'svgwrite>=1.4.0',  # SVG生成
 | ||
|         'numpy>=1.24.0',  # 数值计算
 | ||
|     ]
 | ||
|     
 | ||
|     print("🔧 安装必要的Python包...")
 | ||
|     for package in packages:
 | ||
|         try:
 | ||
|             subprocess.check_call([sys.executable, '-m', 'pip', 'install', package])
 | ||
|             print(f"✅ {package} 安装成功")
 | ||
|         except subprocess.CalledProcessError as e:
 | ||
|             print(f"❌ {package} 安装失败: {e}")
 | ||
|             return False
 | ||
|     return True
 | ||
| 
 | ||
| def convert_ppm_to_png(ppm_path, output_path=None, quality=95):
 | ||
|     """将PPM文件转换为PNG格式"""
 | ||
|     try:
 | ||
|         from PIL import Image
 | ||
|         
 | ||
|         if output_path is None:
 | ||
|             output_path = str(Path(ppm_path).with_suffix('.png'))
 | ||
|         
 | ||
|         # 打开PPM文件
 | ||
|         with Image.open(ppm_path) as img:
 | ||
|             # 转换为RGB模式(PPM通常是RGB)
 | ||
|             if img.mode != 'RGB':
 | ||
|                 img = img.convert('RGB')
 | ||
|             
 | ||
|             # 保存为PNG
 | ||
|             img.save(output_path, 'PNG', optimize=True)
 | ||
|             print(f"✅ PPM -> PNG: {ppm_path} -> {output_path}")
 | ||
|             return output_path
 | ||
|             
 | ||
|     except ImportError:
 | ||
|         print("❌ 需要安装 Pillow: pip install Pillow")
 | ||
|         return None
 | ||
|     except Exception as e:
 | ||
|         print(f"❌ 转换失败: {e}")
 | ||
|         return None
 | ||
| 
 | ||
| def convert_ppm_to_jpg(ppm_path, output_path=None, quality=95):
 | ||
|     """将PPM文件转换为JPG格式"""
 | ||
|     try:
 | ||
|         from PIL import Image
 | ||
|         
 | ||
|         if output_path is None:
 | ||
|             output_path = str(Path(ppm_path).with_suffix('.jpg'))
 | ||
|         
 | ||
|         with Image.open(ppm_path) as img:
 | ||
|             if img.mode != 'RGB':
 | ||
|                 img = img.convert('RGB')
 | ||
|             
 | ||
|             img.save(output_path, 'JPEG', quality=quality, optimize=True)
 | ||
|             print(f"✅ PPM -> JPG: {ppm_path} -> {output_path}")
 | ||
|             return output_path
 | ||
|             
 | ||
|     except ImportError:
 | ||
|         print("❌ 需要安装 Pillow: pip install Pillow")
 | ||
|         return None
 | ||
|     except Exception as e:
 | ||
|         print(f"❌ 转换失败: {e}")
 | ||
|         return None
 | ||
| 
 | ||
| def create_svg_template(image_path, output_path=None):
 | ||
|     """为图像创建SVG模板"""
 | ||
|     try:
 | ||
|         import svgwrite
 | ||
|         from PIL import Image
 | ||
|         
 | ||
|         if output_path is None:
 | ||
|             output_path = str(Path(image_path).with_suffix('.svg'))
 | ||
|         
 | ||
|         # 获取图像尺寸
 | ||
|         with Image.open(image_path) as img:
 | ||
|             width, height = img.size
 | ||
|         
 | ||
|         # 创建SVG文档
 | ||
|         dwg = svgwrite.Drawing(output_path, size=(f"{width}px", f"{height}px"))
 | ||
|         
 | ||
|         # 添加背景矩形
 | ||
|         dwg.add(dwg.rect(insert=(0, 0), size=(width, height), 
 | ||
|                         fill='white', stroke='black', stroke_width=1))
 | ||
|         
 | ||
|         # 添加标题
 | ||
|         dwg.add(dwg.text('胡汉三千年 - 图像模板', 
 | ||
|                         insert=(width//2, 30), 
 | ||
|                         text_anchor='middle',
 | ||
|                         font_size=16,
 | ||
|                         font_family='Arial'))
 | ||
|         
 | ||
|         # 添加说明文字
 | ||
|         dwg.add(dwg.text('此SVG模板需要手动添加具体内容', 
 | ||
|                         insert=(width//2, height-30), 
 | ||
|                         text_anchor='middle',
 | ||
|                         font_size=12,
 | ||
|                         font_family='Arial'))
 | ||
|         
 | ||
|         dwg.save()
 | ||
|         print(f"✅ SVG模板创建: {output_path}")
 | ||
|         return output_path
 | ||
|         
 | ||
|     except ImportError:
 | ||
|         print("❌ 需要安装 svgwrite: pip install svgwrite")
 | ||
|         return None
 | ||
|     except Exception as e:
 | ||
|         print(f"❌ SVG创建失败: {e}")
 | ||
|         return None
 | ||
| 
 | ||
| def batch_convert_directory(directory_path, formats=['png', 'jpg']):
 | ||
|     """批量转换目录中的所有PPM文件"""
 | ||
|     directory = Path(directory_path)
 | ||
|     if not directory.exists():
 | ||
|         print(f"❌ 目录不存在: {directory_path}")
 | ||
|         return
 | ||
|     
 | ||
|     ppm_files = list(directory.rglob('*.ppm'))
 | ||
|     if not ppm_files:
 | ||
|         print(f"❌ 在 {directory_path} 中未找到PPM文件")
 | ||
|         return
 | ||
|     
 | ||
|     print(f"🔍 找到 {len(ppm_files)} 个PPM文件")
 | ||
|     
 | ||
|     converted_count = 0
 | ||
|     for ppm_file in ppm_files:
 | ||
|         print(f"\n📁 处理: {ppm_file}")
 | ||
|         
 | ||
|         for format_type in formats:
 | ||
|             if format_type == 'png':
 | ||
|                 result = convert_ppm_to_png(str(ppm_file))
 | ||
|             elif format_type == 'jpg':
 | ||
|                 result = convert_ppm_to_jpg(str(ppm_file))
 | ||
|             elif format_type == 'svg':
 | ||
|                 result = create_svg_template(str(ppm_file))
 | ||
|             
 | ||
|             if result:
 | ||
|                 converted_count += 1
 | ||
|     
 | ||
|     print(f"\n🎉 批量转换完成! 成功转换 {converted_count} 个文件")
 | ||
| 
 | ||
| def analyze_image_content(image_path):
 | ||
|     """分析图像内容并生成描述"""
 | ||
|     try:
 | ||
|         from PIL import Image
 | ||
|         import numpy as np
 | ||
|         
 | ||
|         with Image.open(image_path) as img:
 | ||
|             width, height = img.size
 | ||
|             mode = img.mode
 | ||
|             
 | ||
|             # 转换为numpy数组进行分析
 | ||
|             img_array = np.array(img)
 | ||
|             
 | ||
|             print(f"📊 图像分析: {image_path}")
 | ||
|             print(f"   尺寸: {width} x {height}")
 | ||
|             print(f"   模式: {mode}")
 | ||
|             print(f"   数据类型: {img_array.dtype}")
 | ||
|             print(f"   形状: {img_array.shape}")
 | ||
|             
 | ||
|             # 分析颜色分布
 | ||
|             if len(img_array.shape) == 3:  # RGB图像
 | ||
|                 unique_colors = len(np.unique(img_array.reshape(-1, img_array.shape[-1]), axis=0))
 | ||
|                 print(f"   唯一颜色数: {unique_colors}")
 | ||
|             
 | ||
|             return {
 | ||
|                 'width': width,
 | ||
|                 'height': height,
 | ||
|                 'mode': mode,
 | ||
|                 'shape': img_array.shape
 | ||
|             }
 | ||
|             
 | ||
|     except Exception as e:
 | ||
|         print(f"❌ 图像分析失败: {e}")
 | ||
|         return None
 | ||
| 
 | ||
| def main():
 | ||
|     parser = argparse.ArgumentParser(description='胡汉三千年项目 - 图像转换工具')
 | ||
|     parser.add_argument('--install', action='store_true', help='安装必要的依赖包')
 | ||
|     parser.add_argument('--convert', type=str, help='转换单个PPM文件')
 | ||
|     parser.add_argument('--batch', type=str, help='批量转换目录中的所有PPM文件')
 | ||
|     parser.add_argument('--analyze', type=str, help='分析图像内容')
 | ||
|     parser.add_argument('--formats', nargs='+', default=['png', 'jpg'], 
 | ||
|                        help='转换格式 (png, jpg, svg)')
 | ||
|     
 | ||
|     args = parser.parse_args()
 | ||
|     
 | ||
|     if args.install:
 | ||
|         if install_requirements():
 | ||
|             print("🎉 所有依赖包安装完成!")
 | ||
|         else:
 | ||
|             print("❌ 依赖包安装失败")
 | ||
|             sys.exit(1)
 | ||
|     
 | ||
|     elif args.convert:
 | ||
|         ppm_path = args.convert
 | ||
|         if not os.path.exists(ppm_path):
 | ||
|             print(f"❌ 文件不存在: {ppm_path}")
 | ||
|             sys.exit(1)
 | ||
|         
 | ||
|         print(f"🔄 转换文件: {ppm_path}")
 | ||
|         for format_type in args.formats:
 | ||
|             if format_type == 'png':
 | ||
|                 convert_ppm_to_png(ppm_path)
 | ||
|             elif format_type == 'jpg':
 | ||
|                 convert_ppm_to_jpg(ppm_path)
 | ||
|             elif format_type == 'svg':
 | ||
|                 create_svg_template(ppm_path)
 | ||
|     
 | ||
|     elif args.batch:
 | ||
|         print(f"🔄 批量转换目录: {args.batch}")
 | ||
|         batch_convert_directory(args.batch, args.formats)
 | ||
|     
 | ||
|     elif args.analyze:
 | ||
|         image_path = args.analyze
 | ||
|         if not os.path.exists(image_path):
 | ||
|             print(f"❌ 文件不存在: {image_path}")
 | ||
|             sys.exit(1)
 | ||
|         
 | ||
|         analyze_image_content(image_path)
 | ||
|     
 | ||
|     else:
 | ||
|         print("🎯 胡汉三千年项目 - 图像转换工具")
 | ||
|         print("\n使用方法:")
 | ||
|         print("  python image_converter.py --install                    # 安装依赖")
 | ||
|         print("  python image_converter.py --convert file.ppm          # 转换单个文件")
 | ||
|         print("  python image_converter.py --batch images/             # 批量转换目录")
 | ||
|         print("  python image_converter.py --analyze file.png           # 分析图像")
 | ||
|         print("  python image_converter.py --formats png jpg svg       # 指定转换格式")
 | ||
| 
 | ||
| if __name__ == '__main__':
 | ||
|     main()
 | ||
| 
 | ||
| 
 |