工具采用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
])))
|