工具采用PIL:Python Imaging Library,图像处理标准库。PIL功能非常强大,但API却非常简单易用。
安装PIL
在Debian/Ubuntu Linux下直接通过apt安装
$
sudo
apt-get
install
python-imaging
|
Windows平台直接通过pip安装
pip
install
pillow
|
批量工具脚本
默认执行方式为:
执行脚本命令 python drawline.py
1.获取当前路径下的
'png'
,
'jpg'
文件
2.绘制宽高占比为0.5,0.5的矩形框
3.保存图片至当前路径下的line文件夹
|
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
|
# -*- coding: utf-8 -*-
from
PIL
import
Image, ImageDraw
import
os, sys
def
drawLine(im, width, height):
'''
在图片上绘制矩形图
:param im: 图片
:param width: 矩形宽占比
:param height: 矩形高占比
:return:
'''
draw
=
ImageDraw.Draw(im)
image_width
=
im.size[
0
]
image_height
=
im.size[
1
]
line_width
=
im.size[
0
]
*
width
line_height
=
im.size[
1
]
*
height
draw.line(
((image_width
-
line_width)
/
2
, (image_height
-
line_height)
/
2
,
(image_width
+
line_width)
/
2
, (image_height
-
line_height)
/
2
),
fill
=
128
)
draw.line(
((image_width
-
line_width)
/
2
, (image_height
-
line_height)
/
2
,
(image_width
-
line_width)
/
2
, (image_height
+
line_height)
/
2
),
fill
=
128
)
draw.line(
((image_width
+
line_width)
/
2
, (image_height
-
line_height)
/
2
,
(image_width
+
line_width)
/
2
, (image_height
+
line_height)
/
2
),
fill
=
128
)
draw.line(
((image_width
-
line_width)
/
2
, (image_height
+
line_height)
/
2
,
(image_width
+
line_width)
/
2
, (image_height
+
line_height)
/
2
),
fill
=
128
)
del
draw
def
endWith(s,
*
endstring):
'''
过滤文件扩展名
:param s: 文件名
:param endstring: 所需过滤的扩展名
:return:
'''
array
=
map
(s.endswith, endstring)
if
True
in
array:
return
True
else
:
return
False
if
__name__
=
=
'__main__'
:
'''
默认执行方式为:
1.获取当前路径下的'png','jpg'文件
2.绘制宽高占比为0.5,0.5的矩形框
3.保存图片至当前路径下的line文件夹
'''
line_w
=
0.5
line_h
=
0.5
try
:
if
sys.argv[
1
]:
line_w
=
float
(sys.argv[
1
])
if
sys.argv[
2
]:
line_h
=
float
(sys.argv[
2
])
except
IndexError:
pass
current_path
=
os.getcwd()
save_path
=
os.path.join(current_path,
'line'
)
file_list
=
os.listdir(current_path)
for
file_one
in
file_list:
# endWith(file_one, '.png', '.jpg') 第二个参数后为过滤格式 以 , 分割
if
endWith(file_one,
'.png'
,
'.jpg'
):
im
=
Image.
open
(file_one)
# drawLine(im,line_w, line_h) 后面两位参数为矩形图宽高占比
drawLine(im, line_w, line_h)
if
not
os.path.exists(save_path):
os.mkdir(save_path)
im.save(
os.path.join(save_path,
str
(file_one.split(
'.'
)[
-
2
])
+
'_line.'
+
str
(file_one.split(
'.'
)[
-
1
])))
|