项目需求
代码优化
有个图片切割需求,找了git上代码复用。但是处理600m的tif文件需要60s左右,不满足项目需求,就对代码进行优化。代码地址:https://github.com/openzoom/deepzoom.py
代码复用克隆后项目结构:
对helloworld-dzi.py文件进行优化
#!/usr/bin/env python3import osimport timeimport PIL.Imageimport PIL.ImageFile# 增加PIL的性能设置PIL.ImageFile.LOAD_TRUNCATED_IMAGES = TruePIL.Image.MAX_IMAGE_PIXELS = None # 禁用像素限制以避免警告import deepzoom# Specify your source image#SOURCE = "helloworld.jpg"FILENAME = "1.tif"TARGET="1.dzi"# Get the directory where this script is locatedscript_dir = os.path.dirname(os.path.abspath(__file__))# Specify your source image using path relative to script locationSOURCE = os.path.join(script_dir,FILENAME )# Format Windows path as a proper file URLSOURCE_URL = SOURCE.replace("\\", "/")if SOURCE_URL[1:3] == ":/": # Check if it's a Windows drive path SOURCE_URL = "file:///" + SOURCE_URL[0].lower() + SOURCE_URL[1:]if not os.path.exists(SOURCE): print(f"错误: 找不到源文件 {SOURCE}") exit(1)# Ensure output directory existsif not os.path.exists("output"): os.makedirs("output")# 优化版的ImageCreator类,专注于性能优化class FastImageCreator(deepzoom.ImageCreator): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # 预定义RESIZE_FILTERS映射,使用最快的最近邻插值 self.resize_filter = 'nearest' def get_image(self, level): """优化的图像缩放方法""" assert (0 <= level and level < self.descriptor.num_levels), "Invalid pyramid level" width, height = self.descriptor.get_dimensions(level) # 如果尺寸相同,直接返回原图 if self.descriptor.width == width and self.descriptor.height == height: return self.image # 使用最快的最近邻插值方法 return self.image.resize((width, height), PIL.Image.Resampling.NEAREST)# 创建深度优化的ImageCreator实例creator = FastImageCreator( tile_size=1024, # 极大增加瓦片大小,大幅减少瓦片数量 tile_overlap=0, # 完全移除重叠以提高性能 tile_format="jpg", # 使用JPEG格式 image_quality=0.5, # 进一步降低JPEG质量以提高速度 copy_metadata=False, # 禁用元数据复制)# Create Deep Zoom image pyramid from source# Use absolute path for output to avoid issuesoutput_path = os.path.abspath(os.path.join("output", TARGET))# 记录开始时间start_time = time.time()# 创建Deep Zoom图像try: # 直接使用优化后的ImageCreator creator.create(SOURCE_URL, output_path) # 计算并显示耗时 elapsed_time = time.time() - start_time print(f"Deep Zoom image created at: {output_path}") print(f"图像创建耗时: {elapsed_time:.2f} 秒")except Exception as e: print(f"创建Deep Zoom图像时出错: {e}") exit(1)效果优化后运行速度缩短至4s左右
转载请注明来自海坡下载,本文标题:《处理优化图片(大图切图dzi优化)》
京公网安备11000000000001号
京ICP备11000001号
还没有评论,来说两句吧...