class UnsupportedFormat(Exception):
def __init__(self, input_type):
return "不支持'{}'模式的转换,请使用为图片地址(path)、PIL.Image(pil)或 OpenCV(cv2)模式".format(self.t)
def __init__(self, original_graph, mask_graph, input_type='path'):
:param original_graph:输入的图片地址、PIL格式、CV2 格式
:param mask_graph:蒙版的图片地址、PIL格式、CV2 格式
:param input_type:输入的类型,有 path:图片地址、pil:pil 类型、cv2 类型
if input_type == 'path':
self.img1 = cv2.imread(original_graph)
self.img2 = cv2.imread(mask_graph)
elif input_type == 'pil':
self.img1 = self.__image_to_opencv(original_graph)
self.img2 = self.__image_to_opencv(mask_graph)
elif input_type == 'cv2':
self.img1 = original_graph
raise UnsupportedFormat(input_type)
def __transparent_back(img):
img = img.convert('RGBA')
color_0 = (255, 255, 255, 255)
color_1 = img.getpixel(dot)
color_1 = color_1[:-1] + (0,)
img.putpixel(dot, color_1)
def save_image(self, mask_flip=False):
:param mask_flip: 蒙版翻转,将蒙版的黑白颜色翻转;True 翻转;False 不使用翻转
timestamp = str(int(time.time()))
img2 = cv2.bitwise_not(self.img2)
image = cv2.add(self.img1, img2)
image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
img = self.__transparent_back(image)
img.save(f"<YOUR_IMAGE_URL>{timestamp}.png")
def __image_to_opencv(image):
img = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)
if __name__ == '__main__':
mm = MatteMatting("<YOUR_IMAGE_PATH>",
mm.save_image(mask_flip=True)