1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
| import multiprocessing
import os
import time
from PIL import Image
import glob
class ImageProcessor:
"""멀티프로세싱 이미지 처리기"""
def __init__(self, num_processes=None):
self.num_processes = num_processes or multiprocessing.cpu_count()
@staticmethod
def resize_image(args):
"""이미지 리사이즈 함수"""
input_path, output_path, size = args
try:
with Image.open(input_path) as img:
# 비율 유지하면서 리사이즈
img.thumbnail(size, Image.Resampling.LANCZOS)
# RGB로 변환 (JPEG 저장을 위해)
if img.mode != 'RGB':
img = img.convert('RGB')
img.save(output_path, 'JPEG', quality=85)
return f"✓ {os.path.basename(input_path)} -> {size}"
except Exception as e:
return f"✗ {os.path.basename(input_path)}: {str(e)}"
@staticmethod
def apply_filter(args):
"""이미지 필터 적용"""
input_path, output_path, filter_type = args
try:
with Image.open(input_path) as img:
# RGB 변환
if img.mode != 'RGB':
img = img.convert('RGB')
# 필터 적용
if filter_type == 'grayscale':
img = img.convert('L').convert('RGB')
elif filter_type == 'sepia':
# 간단한 세피아 효과
pixels = img.load()
for i in range(img.width):
for j in range(img.height):
r, g, b = pixels[i, j]
tr = int(0.393 * r + 0.769 * g + 0.189 * b)
tg = int(0.349 * r + 0.686 * g + 0.168 * b)
tb = int(0.272 * r + 0.534 * g + 0.131 * b)
pixels[i, j] = (min(255, tr), min(255, tg), min(255, tb))
img.save(output_path, 'JPEG', quality=85)
return f"✓ {os.path.basename(input_path)} -> {filter_type}"
except Exception as e:
return f"✗ {os.path.basename(input_path)}: {str(e)}"
@staticmethod
def create_thumbnail(args):
"""썸네일 생성"""
input_path, output_path, size = args
try:
with Image.open(input_path) as img:
# 정사각형 썸네일 생성
img = img.convert('RGB')
# 중앙에서 정사각형으로 자르기
width, height = img.size
min_dimension = min(width, height)
left = (width - min_dimension) // 2
top = (height - min_dimension) // 2
right = left + min_dimension
bottom = top + min_dimension
img = img.crop((left, top, right, bottom))
img = img.resize(size, Image.Resampling.LANCZOS)
img.save(output_path, 'JPEG', quality=85)
return f"✓ {os.path.basename(input_path)} -> thumbnail {size}"
except Exception as e:
return f"✗ {os.path.basename(input_path)}: {str(e)}"
def batch_process(self, input_dir, output_dir, operation, **kwargs):
"""배치 이미지 처리"""
# 입력 이미지 파일들 찾기
image_extensions = ['*.jpg', '*.jpeg', '*.png', '*.bmp', '*.gif']
image_files = []
for ext in image_extensions:
image_files.extend(glob.glob(os.path.join(input_dir, ext)))
image_files.extend(glob.glob(os.path.join(input_dir, ext.upper())))
if not image_files:
print(f"❌ {input_dir}에서 이미지 파일을 찾을 수 없습니다.")
return
# 출력 디렉토리 생성
os.makedirs(output_dir, exist_ok=True)
# 작업 인수 준비
task_args = []
for input_file in image_files:
filename = os.path.splitext(os.path.basename(input_file))[0]
output_file = os.path.join(output_dir, f"{filename}_processed.jpg")
if operation == 'resize':
size = kwargs.get('size', (800, 600))
task_args.append((input_file, output_file, size))
elif operation == 'filter':
filter_type = kwargs.get('filter_type', 'grayscale')
task_args.append((input_file, output_file, filter_type))
elif operation == 'thumbnail':
size = kwargs.get('size', (150, 150))
task_args.append((input_file, output_file, size))
# 작업 함수 선택
work_function = {
'resize': self.resize_image,
'filter': self.apply_filter,
'thumbnail': self.create_thumbnail
}.get(operation)
if not work_function:
print(f"❌ 알 수 없는 작업: {operation}")
return
print(f"🚀 {len(task_args)}개 이미지 처리 시작 ({operation})")
print(f"프로세스 수: {self.num_processes}")
# 멀티프로세싱으로 처리
start_time = time.time()
with multiprocessing.Pool(processes=self.num_processes) as pool:
results = pool.map(work_function, task_args)
end_time = time.time()
# 결과 출력
print(f"\n처리 결과:")
for result in results:
print(result)
success_count = sum(1 for r in results if r.startswith('✓'))
error_count = len(results) - success_count
print(f"\n📊 요약:")
print(f"처리 시간: {end_time - start_time:.2f}초")
print(f"성공: {success_count}, 실패: {error_count}")
print(f"초당 처리: {len(results)/(end_time - start_time):.2f} 이미지/초")
# 사용 예제
def image_processing_demo():
"""이미지 처리 데모"""
# 데모용 샘플 이미지 생성
def create_sample_images():
sample_dir = "sample_images"
os.makedirs(sample_dir, exist_ok=True)
# PIL로 간단한 테스트 이미지 생성
colors = ['red', 'green', 'blue', 'yellow', 'purple']
for i, color in enumerate(colors):
img = Image.new('RGB', (400, 300), color)
img.save(os.path.join(sample_dir, f"sample_{i+1}.jpg"))
return sample_dir
# 샘플 이미지 생성
input_dir = create_sample_images()
# 이미지 프로세서 생성
processor = ImageProcessor(num_processes=2)
# 1. 리사이즈 작업
print("=== 이미지 리사이즈 ===")
processor.batch_process(
input_dir,
"resized_images",
"resize",
size=(200, 150)
)
# 2. 필터 적용
print("\n=== 그레이스케일 필터 ===")
processor.batch_process(
input_dir,
"filtered_images",
"filter",
filter_type="grayscale"
)
# 3. 썸네일 생성
print("\n=== 썸네일 생성 ===")
processor.batch_process(
input_dir,
"thumbnails",
"thumbnail",
size=(100, 100)
)
if __name__ == "__main__":
image_processing_demo()
|