如何通过编程方式将图像转换为灰度图?
推荐几款可异步处理图像转灰度图的工具/库
Python:Pillow(PIL)
结合Python的asyncio可实现异步处理,完美适配「传入图像路径→异步输出灰度图路径」的需求。
示例代码:import asyncio from PIL import Image async def convert_to_grayscale(input_path, output_path): loop = asyncio.get_event_loop() # 用线程池执行同步操作,避免阻塞事件循环 await loop.run_in_executor(None, lambda: Image.open(input_path).convert('L').save(output_path)) return output_path # 调用示例 async def main(): gray_img_path = await convert_to_grayscale("input.jpg", "output_gray.jpg") print(gray_img_path) if __name__ == "__main__": asyncio.run(main())Python:OpenCV
同样可通过asyncio封装异步逻辑,处理大尺寸或批量图像时效率更优。
示例代码:import asyncio import cv2 async def convert_to_grayscale(input_path, output_path): loop = asyncio.get_event_loop() img = await loop.run_in_executor(None, cv2.imread, input_path) gray_img = await loop.run_in_executor(None, cv2.cvtColor, img, cv2.COLOR_BGR2GRAY) await loop.run_in_executor(None, cv2.imwrite, output_path, gray_img) return output_pathNode.js:sharp
专为Node.js打造的高性能图像库,原生支持异步操作,无需额外封装即可满足你的工作流程。
示例代码:const sharp = require('sharp'); async function convertToGrayscale(inputPath, outputPath) { await sharp(inputPath) .grayscale() .toFile(outputPath); return outputPath; } // 调用示例 convertToGrayscale('input.jpg', 'output_gray.jpg') .then(grayPath => console.log(grayPath)) .catch(err => console.error(err));
内容的提问来源于stack exchange,提问作者Jinwook Kim
相关产品推荐
相关产品推荐

