How to Automatically Remove Backgrounds from Your Shopify Product Images Using Python

How to Automatically Remove Backgrounds from Your Shopify Product Images Using Python

Asad-Mahmood
Navigator
300 51 55

What You’ll Need:

  • Python 3.7+ Installed: If not, visit python.org to get started.
  • Shopify Admin API Access: You’ll create a private/custom app to get an API token that allows you to read and write product data.
  • A Few Python Libraries: rembg for background removal, requests for API calls, and Pillow (optional) for image manipulation.

Step-by-Step Guide:

  1. Set Up Your Shopify Admin API Credentials:

    • In your Shopify Admin, go to Settings > Apps and Sales Channels > Develop apps.
    • Click Create an app, give it a meaningful name (e.g., “Image Processor App”).
    • In the Configuration tab, set the Admin API Scopes you need: at least read_products and write_products.
    • Install the app and copy the Admin API Access Token. This token lets your script interact with your product data.
  2. Install Python Dependencies: Open your terminal and run:

 

pip install rembg requests Pillow onnxruntime
​

 

  • Set Your Credentials: You’ll need two key pieces of information:

    • Store Domain: This looks like your-store.myshopify.com.
    • Access Token: The token you just copied 

    Make sure not to share these publicly. Treat them like passwords.

  • The Python Script: Create a file named process_images.py with the following code:

 

import requests
import base64
from rembg import remove
from io import BytesIO

# Replace with your actual store domain and token
SHOPIFY_STORE_DOMAIN = "your-store.myshopify.com"
SHOPIFY_ACCESS_TOKEN = "your_token_here"
SHOPIFY_API_VERSION = "2023-07"

HEADERS = {
    "X-Shopify-Access-Token": SHOPIFY_ACCESS_TOKEN,
    "Content-Type": "application/json"
}

def get_all_products():
    products = []
    url = f"https://{SHOPIFY_STORE_DOMAIN}/admin/api/{SHOPIFY_API_VERSION}/products.json?limit=250"
    while url:
        r = requests.get(url, headers=HEADERS)
        r.raise_for_status()
        data = r.json()
        products.extend(data.get('products', []))
        
        link_header = r.headers.get('Link')
        if link_header and 'rel="next"' in link_header:
            import re
            match = re.search(r'<([^>]+)>; rel="next"', link_header)
            if match:
                url = match.group(1)
            else:
                url = None
        else:
            url = None
    return products

def get_product_images(product_id):
    url = f"https://{SHOPIFY_STORE_DOMAIN}/admin/api/{SHOPIFY_API_VERSION}/products/{product_id}/images.json"
    r = requests.get(url, headers=HEADERS)
    r.raise_for_status()
    return r.json().get('images', [])

def download_image(url):
    r = requests.get(url, stream=True)
    r.raise_for_status()
    return r.content

def remove_bg(image_bytes):
    # rembg's remove function returns image bytes with the background removed
    return remove(image_bytes)

def update_product_image(product_id, image_id, image_bytes):
    # Convert the processed image bytes to base64
    base64_image = base64.b64encode(image_bytes).decode('utf-8')
    url = f"https://{SHOPIFY_STORE_DOMAIN}/admin/api/{SHOPIFY_API_VERSION}/products/{product_id}/images/{image_id}.json"
    payload = {
        "image": {
            "id": image_id,
            "attachment": base64_image
        }
    }

    r = requests.put(url, json=payload, headers=HEADERS)
    r.raise_for_status()
    return r.json().get('image')

def main():
    print("Fetching all products...")
    products = get_all_products()
    print(f"Found {len(products)} products.")

    for product in products:
        product_id = product['id']
        title = product['title']
        print(f"Processing product: {title} (ID: {product_id})")

        images = get_product_images(product_id)
        for img in images:
            img_url = img['src']
            img_id = img['id']
            print(f" - Removing background from image: {img_url}")
            try:
                original_image_bytes = download_image(img_url)
                processed_bytes = remove_bg(original_image_bytes)
                
                # Update the existing image with the processed one
                update_product_image(product_id, img_id, processed_bytes)
                print(f"   Updated existing image (transparent) for product {product_id}")
            except Exception as e:
                print(f"   ✗ Failed to process image: {img_url}")
                print("   Error:", e)

    print("Done processing all products and their images.")

if __name__ == "__main__":
    main()

 



  • Run the Script: Simply run:

 

python process_images.py
​

 


Depending on how many products and images you have, this might take some time. Once complete, check your Shopify Admin product listings. The images should now have transparent backgrounds.



If my solution has been helpful, you can consider supporting me via Buy Me a Coffee.
Hire me: asadmahmood8470@gmail.com
WhatsApp





Replies 0 (0)