Replace the document photo color only 10 lines of Python code

Guide this paper teaches everyone to replace the document photo color through the Python program, and will not be annoyed later.

This article teaches everyone to replace the document on the background color through the Python program, and will not be annoyed again after replacing the document.


First remove the background color of the original photo to add new background color

The steps are very simple, the ideas are clear, it is also very simple, the ten lines of code can be customized, guarantee that you will definitely!

1. Go to the original background color

Importos # Remove the background color Os.System (‘BackgroundRemover-i “‘ + str (in_path) + ‘” – o “cg_output.jpg”)

IN_PATH is the path to the original photo, cg_output.jpg is the photo after the background

Tip: BackgroundRemover This library can refer to my previous article (a line of Python code to remove photos)

2. Add a new background color

Background color plus # no_bg_image = ( “cg_output.jpg”) x, y = no_bg_image.sizenew_image = ( ‘RGBA’, no_bg_image.size, color = color) new_image.paste (no_bg_image, (0, 0, x, y), NO_BG_IMAGE) NEW_IMAGE.SAVE (OUT_PATH)

OUT_PATH is the photo path behind the background color, and the color is the new color to replace, fill in the corresponding English, such as red: RED

Color = “red” # ºì: red, blue: blue, black: black, white: White

Complete code

ImportosFromPilimportImage # Enter in_path = “replace.jpg” # Out_Path = “out.png” # To replace background color color = “red” # ºì: red, blue: blue, black: black, white: white # Remove background color Os.system (‘BackgroundRemover-I “‘ + STR (In_Path) + ‘” – O “cg_output.jpg”) # plus background color NO_BG_IMAGE = Image.Open (“cg_output.jpg”) x, y = no_bg_image. Sizenew_image = (‘RGBA’, NO_BG_IMAGE.SIZE, Color = Color) NEW_IMAGE.PASTE (NO_BG_IMAGE, (0, X, Y), NO_BG_IMAGE) NEW_IMAGE.SAVE (OUT_PATH)

Code is generally step:

Pet.png on a background color of replace.jpg (photo), red background.

Here, the reader is reminded, the output (out.png) is saved to the PNG format, and other formats are wrong with the JPG program.

Sample effect: (image source network)

The left is the original picture (blue), the right side is a photo

(Blue change into red)


Python replaces the document photo color is not difficult, the idea is to remove the background, add a new background color, I believe you have learned here.

Originally from: