# -*- 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 ])))
|