[docs]@OPERATORS.register_module(OP_NAME)@LOADED_IMAGES.register_module(OP_NAME)classImageRemoveBackgroundMapper(Mapper):""" Mapper to remove background of images """
[docs]def__init__(self,alpha_matting:bool=False,alpha_matting_foreground_threshold:int=240,alpha_matting_background_threshold:int=10,alpha_matting_erode_size:int=10,bgcolor:Optional[Tuple[int,int,int,int]]=None,*args,**kwargs):""" Initialization method. alpha_matting (bool, optional): Flag indicating whether to use alpha matting. Defaults to False. alpha_matting_foreground_threshold (int, optional): Foreground threshold for alpha matting. Defaults to 240. alpha_matting_background_threshold (int, optional): Background threshold for alpha matting. Defaults to 10. alpha_matting_erode_size (int, optional): Erosion size for alpha matting. Defaults to 10. bgcolor (Optional[Tuple[int, int, int, int]], optional): Background color for the cutout image. Defaults to None. *args (Optional[Any]): Additional positional arguments. **kwargs (Optional[Any]): Additional keyword arguments. """super().__init__(*args,**kwargs)self._init_parameters=self.remove_extra_parameters(locals())self.alpha_matting=alpha_mattingself.alpha_matting_foreground_threshold= \
alpha_matting_foreground_thresholdself.alpha_matting_background_threshold= \
alpha_matting_background_thresholdself.alpha_matting_erode_size=alpha_matting_erode_sizeself.bgcolor=bgcolor
[docs]defprocess_single(self,sample,context=False):# there is no image in this sampleifself.image_keynotinsampleor \
notsample[self.image_key]:return[]ifFields.source_filenotinsampleornotsample[Fields.source_file]:sample[Fields.source_file]=sample[self.image_key]# load imagesloaded_image_keys=sample[self.image_key]sample,images=load_data_with_context(sample,context,loaded_image_keys,load_image)processed={}forimage_keyinloaded_image_keys:ifimage_keyinprocessed:continueremove_image_key=transfer_filename(image_key,OP_NAME,**self._init_parameters)name,_=os.path.splitext(remove_image_key)remove_image_key=f'{name}.png'ifnotos.path.exists(remove_image_key)orremove_image_keynotinimages:rembg_image=rembg.remove(images[image_key],alpha_matting=self.alpha_matting,alpha_matting_foreground_threshold=self.alpha_matting_foreground_threshold,alpha_matting_background_threshold=self.alpha_matting_background_threshold,alpha_matting_erode_size=self.alpha_matting_erode_size,bgcolor=self.bgcolor)rembg_image.save(remove_image_key,format='PNG')images[remove_image_key]=rembg_imageifcontext:sample[Fields.context][remove_image_key]=rembg_imageprocessed[image_key]=remove_image_key# when the file is modified, its source file needs to be updated.fori,valueinenumerate(loaded_image_keys):ifsample[Fields.source_file][i]!=valueandprocessed[value]!=value:sample[Fields.source_file][i]=processed[value]sample[self.image_key]=[processed[key]forkeyinloaded_image_keys]returnsample