-
-
Notifications
You must be signed in to change notification settings - Fork 130
/
utils.py
400 lines (330 loc) · 11.7 KB
/
utils.py
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
import logging
import platform
import re
import shutil
import subprocess
from pathlib import Path
from PIL import Image
from PIL import ImageDraw
from PIL import ImageOps
from enums.constant import TRANSPARENT
if platform.system() == 'Windows':
EXIFTOOL_PATH = Path('./exiftool/exiftool.exe')
ENCODING = 'gbk'
elif shutil.which('exiftool') is not None:
EXIFTOOL_PATH = shutil.which('exiftool')
ENCODING = 'utf-8'
else:
EXIFTOOL_PATH = Path('./exiftool/exiftool')
ENCODING = 'utf-8'
logger = logging.getLogger(__name__)
def get_file_list(path):
"""
获取 jpg 文件列表
:param path: 路径
:return: 文件名
"""
path = Path(path, encoding=ENCODING)
return [file_path for file_path in path.iterdir()
if file_path.is_file() and file_path.suffix in ['.jpg', '.jpeg', '.JPG', '.JPEG', '.png', '.PNG']]
def get_exif(path) -> dict:
"""
获取exif信息
:param path: 照片路径
:return: exif信息
"""
exif_dict = {}
try:
output_bytes = subprocess.check_output([EXIFTOOL_PATH, '-d', '%Y-%m-%d %H:%M:%S%3f%z', path])
output = output_bytes.decode('utf-8', errors='ignore')
lines = output.splitlines()
utf8_lines = [line for line in lines]
for line in utf8_lines:
# 将每一行按冒号分隔成键值对
kv_pair = line.split(':')
if len(kv_pair) < 2:
continue
key = kv_pair[0].strip()
value = ':'.join(kv_pair[1:]).strip()
# 将键中的空格移除
key = re.sub(r'\s+', '', key)
key = re.sub(r'/', '', key)
# 将键值对添加到字典中
exif_dict[key] = value
for key, value in exif_dict.items():
# 过滤非 ASCII 字符
value_clean = ''.join(c for c in value if ord(c) < 128)
# 将处理后的值更新到 exif_dict 中
exif_dict[key] = value_clean
except Exception as e:
logger.error(f'get_exif error: {path} : {e}')
return exif_dict
def insert_exif(source_path, target_path) -> None:
"""
复制照片的 exif 信息
:param source_path: 源照片路径
:param target_path: 目的照片路径
"""
try:
# 将 exif 信息转换为字节串
subprocess.check_output([EXIFTOOL_PATH, '-tagsfromfile', source_path, '-overwrite_original', target_path])
except ValueError as e:
logger.exception(f'ValueError: {source_path}: cannot insert exif {str(e)}')
TINY_HEIGHT = 800
def remove_white_edge(image):
"""
移除图片白边
:param image: 图片对象
:return: 移除白边后的图片对象
"""
# 获取像素信息
pixels = image.load()
# 获取图像大小
width, height = image.size
# 计算最小的 X、Y、最大的 X、Y 坐标
min_x, min_y = width - 1, height - 1
max_x, max_y = 0, 0
for y in range(height):
for x in range(width):
if pixels[x, y] != (255, 255, 255):
min_x = min(min_x, x)
min_y = min(min_y, y)
max_x = max(max_x, x)
max_y = max(max_y, y)
# 计算新的图像大小
new_width = max_x - min_x + 1
new_height = max_y - min_y + 1
# 裁剪图像
new_image = image.crop((min_x, min_y, max_x + 1, max_y + 1))
return new_image
def concatenate_image(images, align='left'):
"""
将多张图片拼接成一列
:param images: 图片对象列表
:param align: 对齐方向,left/center/right
:return: 拼接后的图片对象
"""
widths, heights = zip(*(i.size for i in images))
sum_height = sum(heights)
max_width = max(widths)
new_img = Image.new('RGBA', (max_width, sum_height), color=TRANSPARENT)
x_offset = 0
y_offset = 0
if 'left' == align:
for img in images:
new_img.paste(img, (0, y_offset))
y_offset += img.height
elif 'center' == align:
for img in images:
x_offset = int((max_width - img.width) / 2)
new_img.paste(img, (x_offset, y_offset))
y_offset += img.height
elif 'right' == align:
for img in images:
x_offset = max_width - img.width # 右对齐
new_img.paste(img, (x_offset, y_offset))
y_offset += img.height
return new_img
def padding_image(image, padding_size, padding_location='tb', color=TRANSPARENT) -> Image.Image:
"""
在图片四周填充白色像素
:param image: 图片对象
:param padding_size: 填充像素大小
:param padding_location: 填充位置,top/bottom/left/right
:return: 填充白色像素后的图片对象
"""
if image is None:
return None
total_width, total_height = image.size
x_offset, y_offset = 0, 0
if 't' in padding_location:
total_height += padding_size
y_offset += padding_size
if 'b' in padding_location:
total_height += padding_size
if 'l' in padding_location:
total_width += padding_size
x_offset += padding_size
if 'r' in padding_location:
total_width += padding_size
padding_img = Image.new('RGBA', (total_width, total_height), color=color)
padding_img.paste(image, (x_offset, y_offset))
return padding_img
def square_image(image, auto_close=True) -> Image.Image:
"""
将图片按照正方形进行填充
:param auto_close: 是否自动关闭图片对象
:param image: 图片对象
:return: 填充后的图片对象
"""
# 计算图片的宽度和高度
width, height = image.size
if width == height:
return image
# 计算需要填充的白色区域大小
delta_w = abs(width - height)
padding = (delta_w // 2, 0) if width < height else (0, delta_w // 2)
square_img = ImageOps.expand(image, padding, fill='white')
if auto_close:
image.close()
# 返回正方形图片对象
return square_img
def resize_image_with_height(image, height, auto_close=True):
"""
按照高度对图片进行缩放
:param image: 图片对象
:param height: 指定高度
:return: 按照高度缩放后的图片对象
"""
# 获取原始图片的宽度和高度
width, old_height = image.size
# 计算缩放后的宽度
scale = height / old_height
new_width = round(width * scale)
# 进行等比缩放
resized_image = image.resize((new_width, height), Image.LANCZOS)
# 关闭图片对象
if auto_close:
image.close()
# 返回缩放后的图片对象
return resized_image
def resize_image_with_width(image, width, auto_close=True):
"""
按照宽度对图片进行缩放
:param image: 图片对象
:param width: 指定宽度
:return: 按照宽度缩放后的图片对象
"""
# 获取原始图片的宽度和高度
old_width, height = image.size
# 计算缩放后的宽度
scale = width / old_width
new_height = round(height * scale)
# 进行等比缩放
resized_image = image.resize((width, new_height), Image.LANCZOS)
# 关闭图片对象
if auto_close:
image.close()
# 返回缩放后的图片对象
return resized_image
def append_image_by_side(background, images, side='left', padding=200, is_start=False):
"""
将图片横向拼接到背景图片中
:param background: 背景图片对象
:param images: 图片对象列表
:param side: 拼接方向,left/right
:param padding: 图片之间的间距
:param is_start: 是否在最左侧添加 padding
:return: 拼接后的图片对象
"""
if 'right' == side:
if is_start:
x_offset = background.width - padding
else:
x_offset = background.width
images.reverse()
for i in images:
if i is None:
continue
i = resize_image_with_height(i, background.height, auto_close=False)
x_offset -= i.width
x_offset -= padding
background.paste(i, (x_offset, 0))
else:
if is_start:
x_offset = padding
else:
x_offset = 0
for i in images:
if i is None:
continue
i = resize_image_with_height(i, background.height, auto_close=False)
background.paste(i, (x_offset, 0))
x_offset += i.width
x_offset += padding
def text_to_image(content, font, bold_font, is_bold=False, fill='black') -> Image.Image:
"""
将文字内容转换为图片
"""
if is_bold:
font = bold_font
if content == '':
content = ' '
_, _, text_width, text_height = font.getbbox(content)
image = Image.new('RGBA', (text_width, text_height), color=TRANSPARENT)
draw = ImageDraw.Draw(image)
draw.text((0, 0), content, fill=fill, font=font)
return image
def merge_images(images, axis=0, align=0):
"""
拼接多张图片
:param images: 图片对象列表
:param axis: 0 水平拼接,1 垂直拼接
:param align: 0 居中对齐,1 底部/右对齐,2 顶部/左对齐
:return: 拼接后的图片对象
"""
# 获取每张图像的 size
widths, heights = zip(*(img.size for img in images))
# 计算输出图像的尺寸
if axis == 0: # 水平拼接
total_width = sum(widths)
max_height = max(heights)
else: # 垂直拼接
total_width = max(widths)
max_height = sum(heights)
# 创建输出图像
output_image = Image.new('RGBA', (total_width, max_height), color=TRANSPARENT)
# 拼接图像
x_offset, y_offset = 0, 0
for img in images:
if axis == 0: # 水平拼接
if align == 1: # 底部对齐
y_offset = max_height - img.size[1]
elif align == 2: # 顶部对齐
y_offset = 0
else: # 居中排列
y_offset = (max_height - img.size[1]) // 2
output_image.paste(img, (x_offset, y_offset))
x_offset += img.size[0]
else: # 垂直拼接
if align == 1: # 右对齐
x_offset = total_width - img.size[0]
elif align == 2: # 左对齐
x_offset = 0
else: # 居中排列
x_offset = (total_width - img.size[0]) // 2
output_image.paste(img, (x_offset, y_offset))
y_offset += img.size[1]
return output_image
def calculate_pixel_count(width: int, height: int) -> str:
# 计算像素总数
pixel_count = width * height
# 计算百万像素数
megapixel_count = pixel_count / 1000000.0
# 返回结果字符串
return f"{megapixel_count:.2f} MP"
def extract_attribute(data_dict: dict, *keys, default_value: str = '', prefix='', suffix='') -> str:
"""
从字典中提取对应键的属性值
:param data_dict: 包含属性值的字典
:param keys: 一个或多个键
:param default_value: 默认值,默认为空字符串
:return: 对应的属性值或空字符串
"""
for key in keys:
if key in data_dict:
return data_dict[key] + suffix
return default_value
def extract_gps_lat_and_long(lat: str, long: str):
# 提取出纬度和经度主要部分
lat_deg, _, lat_min = re.findall(r"(\d+ deg \d+)", lat)[0].split()
long_deg, _, long_min = re.findall(r"(\d+ deg \d+)", long)[0].split()
# 提取出方向(北 / 南 / 东 / 西)
lat_dir = re.findall(r"([NS])", lat)[0]
long_dir = re.findall(r"([EW])", long)[0]
latitude = f"{lat_deg}°{lat_min}'{lat_dir}"
longitude = f"{long_deg}°{long_min}'{long_dir}"
return latitude, longitude
def extract_gps_info(gps_info: str):
lat, long = gps_info.split(", ")
return extract_gps_lat_and_long(lat, long)