Python 图像打马赛克

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值