banner
肥皂的小屋

肥皂的小屋

github
steam
bilibili
douban
tg_channel

Python--a small program to change the background color of ID photos

Cause#

I saw an article introducing an AI background removal library called removebg.

Click me to go to GitHub, click me to go to the official website to change the image background online.

As for background removal, I have helped friends with this before. I originally followed doyoudo's tutorial. You need to register and log in to view directly on the website.

If you don't want to register, you can watch it on Youku. Here, I would like to recommend the doyoudo website (please send money if you see this, thank you):

doyoudo is a fresh tutorial website for audio and video editing software.

After getting familiar with the tutorial, you can edit a picture in about 10 minutes. However! Now that there is this AI background removal library removebg, I definitely want to try its effect.

This library is roughly described as follows:

The default generated image format size is standard, and you can process up to 50 photos for free each month. If you want to generate high-definition or even 4K images or process more photos, you need to pay. The price is about 1 yuan per image.

So I plan to wrap this core code and continue to create a small program using PyQt5 to strengthen my PyQt5 skills and see if I can learn something new.

Non-GUI Version#

** Note: The generated image will be saved in the original image's directory, and the file name will change from image_name.image_extension to image_name.image_extension_no_bg.png **

Replace Background#

After registering and logging in, go to the website API interface to get your own API, and then you can achieve basic image background replacement with the following lines of code:

from removebg import RemoveBg
rmbg = RemoveBg("your_apikey", "error.log")
rmbg.remove_background_from_img_file(r"C:\Users\soapffz\Desktop\640_2.jpg") # Image location

The effect is as follows:

image

image

image

For the speed of image loading, the quality here has been severely compressed, so please don't mind.

** The core library used in this article only has the function of removing the background from images **, and filling it with other colors is achieved using Image from PIL:

Fill Color#

from PIL import Image
img = Image.open(r'640.png').convert("RGBA")
x, y = img.size
card = Image.new("RGBA", img.size, (0, 0, 255))
card.paste(img, (0, 0, x, y), img)
card.save("640_2.jpg", format="png")

The effect is as follows:

image

GUI Version#

** Here I would like to add some tips about PyQt5 that I have been using but keep forgetting to mention **

Design GUI#

Basic design tutorials can be found in the article <<Building a Local IP Proxy Pool (Completed)>>, which can be found in the Python directory.

The GUI design diagram is shown below:

image

File Selection#

Reference article: Using QFileDialog in PyQt5

Select a single file:

from os import path
from sys import argv

    self.exe_path = path.dirname(argv[0])  # Get the current program's running path
    self.pushButton.clicked.connect(self.chosepic) # Trigger function when the file selection button is pressed

    def chosepic(self):
        # Select an image
        file_name = QtWidgets.QFileDialog.getOpenFileName(
            self, "Select File", self.exe_path, "Pic Files (*.png;*.jpg);;Text Files (*.txt)")[0]   # Set file extension filter, separated by double semicolons
        if file_name == "":
            print("User canceled selection")
            return
        print("The file you selected is:", file_name)

Select a single folder:

from os import path
from sys import argv

    self.exe_path = path.dirname(argv[0])  # Get the current program's running path
    self.pushButton.clicked.connect(self.chosedir) # Trigger function when the folder selection button is pressed
    def chosedir(self):
        # Select the folder containing images
        dir_name = QtWidgets.QFileDialog.getExistingDirectory(
            self, "Select Folder",  self.exe_path)
        if dir_name == "":
            print("\nSelection canceled")
            return
        print("The folder you selected is:", dir_name)

Here, I only introduced two commonly used methods. For selecting multiple files, you can use the method of selecting a single folder and then checking the file extensions. For other methods, please refer to the reference article.

Popup Display Implementation#

Common Functions:#

# Information Box
QMessageBox.information(self, 'Box Name', 'Content', Buttons, Default Button)
# Question Box
QMessageBox.question(self, 'Box Name', 'Content', Buttons, Default Button)
# Warning Box
QMessageBox.warning(self, 'Box Name', 'Content', Buttons, Default Button)
# Critical Box
QMessageBox.critical(self, 'Box Name', 'Content', Buttons, Default Button)
# About Box
QMessageBox.about(self, 'Box Name', 'Content')

Example:

from PyQt5.QtWidgets import QMessageBox

# Exit confirmation box
reply = QMessageBox.question(self, 'Exit', 'Are you sure you want to exit?', QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel, QMessageBox.Cancel)
if reply == QMessageBox.Yes:
	print('Exiting')
else:
	print('Not exiting')

image

Custom Message Box#

# Create a question box, note it is Question
self.box = QMessageBox(QMessageBox.Question, 'Exit', 'Are you sure you want to exit?')

# Add buttons, can use Chinese
yes = self.box.addButton('Yes', QMessageBox.YesRole)
no = self.box.addButton('Cancel', QMessageBox.NoRole)

# Set the icon in front of the content of the message box
self.box.setIcon(1)

# Set the position of the message box, size cannot be set
self.box.setGeometry(500, 500, 0, 0)

# Show the question box
self.box.show()

if self.box.clickedButton() == yes:
	print('Exiting')
else:
	print('Not exiting')

image

Reference articles:

Generally set on the label component, just fill in the text normally during design, then make the following settings:

self.label_getapi.setText("<a href='https://www.remove.bg/api'>Click me to get APIKEY:</a>") # Set hyperlink text
self.label_getapi.setOpenExternalLinks(True) # Allow the default browser to access hyperlinks

Checkbox Calls the Same Function to Check Status#

In my program design, it is necessary to generate images without background color first, and then select other background colors.

So how can I get the colors to be converted? This can be achieved using the following method:

        self.bg_color_chose_l = []  # List of colors to be converted
        self.checkBox_white.stateChanged.connect(self.checkstate)
        self.checkBox_blue.stateChanged.connect(self.checkstate)
        self.checkBox_red.stateChanged.connect(self.checkstate)
        self.pushButton_begin.clicked.connect(self.begin)
    def checkstate(self, state):
        # Used to check which color conversion options have been checked
        # Get the checkbox that sent the signal
        which_checkbox = self.sender()
        if state == QtCore.Qt.Unchecked:
            self.insert_msg_to_disp(
                "User no longer wants a {} background image".format(which_checkbox.text()))
            self.bg_color_chose_l.remove(which_checkbox.text())
        if state == QtCore.Qt.Checked:
            self.insert_msg_to_disp(
                "User wants a {} background image".format(which_checkbox.text()))
            self.bg_color_chose_l.append(which_checkbox.text())
        if len(self.bg_color_chose_l) == 0:
            self.insert_msg_to_disp("No background selected now!")
        else:
            self.insert_msg_to_disp(
                "The background colors the user wants now are: {}".format(self.bg_color_chose_l))

The effect is as follows:

image

Reference article: PyQt5 Notes - CheckBox

Refresh Page#

In places where the program may lag, especially add this command to the first line of the for loop:

QtWidgets.QApplication.processEvents()

Final Effect#

** Note that in actual use, it was found that when the background of the image is too complex, the background cannot be successfully removed **

** An error will be reported in error.log as follows:**

ERROR:root:Unable to save C:\Users\soapffz\Desktop\xdx.jpg_no_bg.png due to could not identify foreground in image. for details and recommendations see https://www.remove.bg/supported-images.

** Therefore, do not choose overly complex images for experimentation; try to select portraits with less complex backgrounds **

The final effect of converting a single file is as follows:

image

The final effect of converting multiple files is as follows:

image

The article is finished. (Staying up late until 2:30 AM)


Download link for the finished product (future updates will be posted here):

(2019-07-24 2:30 AM): https://www.lanzous.com/i54q96f

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.