当前位置:   article > 正文

Python 图像打马赛克_python图片马赛克

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)
  • 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
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/362076
推荐阅读
相关标签
  

闽ICP备14008679号