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
<code>import numpy as np
import cv2</code>2. Install OpenCV
<code>pip install OpenCV-python</code>3. Load image
<code>img = cv2.imread('timg.jpg')</code>4. Resize image
<code>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)</code>5. Display and convert to HSV, define color range
<code>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])</code>6. Create binary mask
<code>mask = cv2.inRange(hsv, lower_blue, upper_blue)
cv2.imshow('Mask', mask)</code>7. Erosion
<code>erosion = cv2.erode(mask, None, iterations=1)
cv2.imshow('erosion', erosion)</code>8. Dilation
<code>dilation = cv2.dilate(mask, None, iterations=1)
cv2.imshow('dilation', dilation)</code>9. Replace background color where mask is white
<code>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)</code>10. Save result and clean up
<code>cv2.imwrite('ting.png', img)
cv2.waitKey(0) # wait indefinitely
cv2.destroyAllWindows() # close all windows</code>The 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.
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.