from PIL import Image
def do_mask(self,img_file, mask_box, save_file):
"""
:param img_file:
:param mask_box:[左上x,左上y,width,height]
:param save_file:
:return:
"""
def mosaic(img, fx, fy, tx, ty):
c = img.crop((fx, fy, tx, ty))
c = _mosaic(c)
img.paste(c, (fx, fy, tx, ty))
return img
def _mosaic(img):
s = img.size
img = img.resize((1, 1))
img = img.resize(s)
return img
img = Image.open(img_file)
x, y, w, h = mask_box
mosaic_size = 20
for i in range(int(w / mosaic_size) + 1):
for j in range(int(h / mosaic_size) + 1):
if (mosaic_size * (i + 1) > w and mosaic_size * (j + 1) < h):
fx, fy, tx, ty = (x + mosaic_size * i, y + mosaic_size * j, w + x, mosaic_size * (j + 1) + y)
elif (mosaic_size * (i + 1) < w and mosaic_size * (j + 1) > h):
fx, fy, tx, ty = (x + mosaic_size * i, y + mosaic_size * j, mosaic_size * (i + 1) + x, h + y)
elif (mosaic_size * (i + 1) > w and mosaic_size * (j + 1) > h):
fx, fy, tx, ty = (x + mosaic_size * i, y + mosaic_size * j, w + x, h + y)
else:
fx, fy, tx, ty = (
x + mosaic_size * i, y + mosaic_size * j, mosaic_size * (i + 1) + x, mosaic_size * (j + 1) + y)
if tx<=0:
tx = 1
if ty <= 0:
ty = 1
img = mosaic(img, fx, fy, tx, ty)
img.save(save_file)
Python 图像打马赛克
最新推荐文章于 2024-07-15 11:25:12 发布