Python 멀티프로세싱으로 이미지 리사이징 속도 개선
문제 상황
사용자가 업로드한 원본 이미지를 여러 사이즈로 리사이징하는 배치 작업이 있었다. 단일 프로세스로 순차 처리하니 5000장 기준 약 40분이 걸렸다.
기존 코드는 Pillow로 이미지를 열고 resize하는 단순한 루프였다.
from PIL import Image
import os
def resize_image(input_path, output_path, size):
img = Image.open(input_path)
img.thumbnail(size, Image.ANTIALIAS)
img.save(output_path, quality=85)
for image_file in image_files:
resize_image(image_file, output_file, (800, 600))
해결 방법
이미지 리사이징은 CPU 바운드 작업이므로 멀티프로세싱이 효과적이다. multiprocessing.Pool을 사용해 CPU 코어 수만큼 프로세스를 띄웠다.
from multiprocessing import Pool, cpu_count
from PIL import Image
import os
def resize_image(args):
input_path, output_path, size = args
try:
img = Image.open(input_path)
img.thumbnail(size, Image.ANTIALIAS)
img.save(output_path, quality=85)
return True
except Exception as e:
print(f"Error: {input_path} - {e}")
return False
if __name__ == '__main__':
tasks = [(input_path, output_path, (800, 600)) for ...]
with Pool(cpu_count()) as pool:
results = pool.map(resize_image, tasks)
print(f"Success: {sum(results)}/{len(results)}")
결과
4코어 머신에서 처리 시간이 40분에서 11분으로 줄었다. 프로세스 생성 오버헤드가 있지만 이미지 처리 비용이 훨씬 커서 충분히 효과적이었다.
주의할 점은 if __name__ == '__main__' 가드를 반드시 써야 한다는 것. Windows 환경에서 이게 없으면 무한히 프로세스가 생성된다.
또한 메모리 사용량도 체크해야 한다. 너무 큰 이미지를 동시에 여러 개 열면 메모리 부족이 발생할 수 있다. 필요하면 Pool의 프로세스 수를 조정하면 된다.