📜  éliminer le 背景图片 python (1)

📅  最后修改于: 2023-12-03 15:00:40.981000             🧑  作者: Mango

Python Code to Remove Background Image

Are you tired of manually removing background images from your pictures? Use Python to automate this task!

Here is a simple script that uses OpenCV library to remove background image:

import cv2

def remove_background(img_path):
    # Load image in grayscale mode
    img = cv2.imread(img_path, 0)

    # Remove noise using GaussianBlur
    img = cv2.GaussianBlur(img, (5, 5), 0)

    # Threshold the image to get a binary image
    _, thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)

    # Apply morphology operations to remove small noise in the image
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
    opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)

    # Find the contour of the object
    contours, _ = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnt = max(contours, key=cv2.contourArea)

    # Create a mask of the object and apply it to the original image
    mask = cv2.drawContours(img.copy(), [cnt], 0, (0,0,255), cv2.FILLED)
    result = cv2.bitwise_and(cv2.imread(img_path), cv2.imread(img_path), mask=mask)

    # Save the result
    cv2.imwrite('result.jpg', result)

    return '![original image]({})\n\n![background removed]({})'.format(img_path, 'result.jpg')

This function, remove_background, takes an image path as an argument, loads the image in grayscale mode, applies several image processing techniques to remove the background, and saves the result in a new file. The function then returns a Markdown-formatted string that contains both the original image and the background removed image.

To use this function, simply call it with the path of the image you want to process:

print(remove_background('my_image.png'))

This will output a Markdown-formatted string with the original image and the background removed image.

Now you can easily automate the task of removing background images from your pictures using Python!