Source code for odoo_xmlrpc_twisted.functions.remove_background
"""Remove the background from an image."""importosimportbase64fromioimportBytesIOfromPILimportImagefromrembgimportremove,new_session# Use lightweight background removal modelos.environ["U2NET_MODEL_NAME"]="u2netp"# ------- end of the initialisation -------
[docs]defremove_background(image):""" Remove the background from an image using the Python library "rembg" with the function "remove". See https://github.com/danielgatis/rembg. Result is the adapted image stream. """# Decode base64 string to bytesimage_bytes=base64.b64decode(image)# Open imageimage_input=Image.open(BytesIO(image_bytes))# Remove background in a sessiontry:# Create session with lightweight modelsession=new_session(model_name="u2netp")# Remove backgroundimage_output=remove(image_input,session=session)finally:image_input.close()# Ensure image file is closed# Convert result to base64 in 3 steps:# 1. create a buffer to hold the image databuffered=BytesIO()# 2. save the image to the buffer in PNG formatimage_output.save(buffered,format="PNG")# 3. convert the image data in the buffer to a base64-encoded string image_result=base64.b64encode(buffered.getvalue())return(image_result)