One-Click Background Replacement for ID Photos Using Python OpenCV
This tutorial demonstrates how to use Python, OpenCV, and NumPy on Windows to import an image, resize it, convert it to HSV, apply color-based masking, perform erosion and dilation, replace the background color, and finally save the processed photo with a single script.
In daily life we often need ID photos with different background colors (red, white, blue). This guide shows how to replace the background of an ID photo automatically without manual cropping, using Python and OpenCV.
Knowledge Points
1. Image processing 2. OpenCV 3. NumPy 4. Basic Python knowledge
Environment
Windows, PyCharm, Python 3
Steps
1. Import libraries
import numpy as np
import cv22. Install OpenCV pip install OpenCV-python 3. Load image img = cv2.imread('timg.jpg') 4. Resize image
rows, cols, channels = img.shape
print(rows, cols, channels)
img = cv2.resize(img, None, fx=0.5, fy=0.5)
rows, cols, channels = img.shape
print(rows, cols, channels)5. Display and convert to HSV, define color range
cv2.imshow('img', img)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
cv2.imshow('hsv', hsv)
lower_blue = np.array([90, 70, 90])
upper_blue = np.array([110, 255, 255])6. Create binary mask
mask = cv2.inRange(hsv, lower_blue, upper_blue)
cv2.imshow('Mask', mask)7. Erosion
erosion = cv2.erode(mask, None, iterations=1)
cv2.imshow('erosion', erosion)8. Dilation
dilation = cv2.dilate(mask, None, iterations=1)
cv2.imshow('dilation', dilation)9. Replace background color where mask is white
for i in range(rows):
for j in range(cols):
if dilation[i, j] == 255:
img[i, j] = (0, 0, 255) # BGR (red)
cv2.imshow('res', img)10. Save result and clean up
cv2.imwrite('ting.png', img)
cv2.waitKey(0) # wait indefinitely
cv2.destroyAllWindows() # close all windowsThe script processes the input image, isolates the desired background color, replaces it with red (or any chosen color), and saves the final image, providing a quick solution for generating ID photos with custom backgrounds.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
