Skip to content

实例:Logo图片裁剪, 用PIL去除图像背景

python
from PIL import Image

a = 'logo.png'

COLOR_TRANSPARENT = (0,0,0,0)
COLOR_BLACK       = (3,12,30,255)

class ImageHelper:

    def __init__(self, im):
        self.im = im
        self.h = self.im.height
        self.w = self.im.width
        self.im_data = self.im.getdata()
        self.pos_data = self._get_posdata()

    def _get_posdata(self):
        i = 0
        posdata = dict()
        for y in range(self.h):
            for x in range(self.w):
                posdata[(x,y)] = self.im_data[i]
                i += 1
        return posdata

    def is_near_color(self, pos, color):
        x, y = pos
        for x,y in [(x,y-1), (x,y+1), (x-1,y), (x+1,y)]:
            if (x,y) in self.pos_data and self.pos_data[(x,y)] == color:
                return True, (x,y)
        return False, None

    def replace_color(self, old_color, color):
        for pos, col in ih.pos_data.items():
            new_color = color if col == old_color else col
            ih.pos_data[pos] = new_color
            self.im.putpixel(pos, new_color)

    def reverse_replace_color(self, old_colors, new_color):
        for pos, col in ih.pos_data.items():
            if col not in old_colors:
                ih.pos_data[pos] = new_color
                self.im.putpixel(pos, new_color)

    def save(self, filename):
        self.im.save(filename)


ih = ImageHelper(Image.open(a).convert("RGBA"))
ih.reverse_replace_color(((5,242,242,255),(67,154,255,255)), COLOR_TRANSPARENT)
ih.save('new.png')

Released under the MIT License.