Part.I Introduction
本文将介绍如何用 OpenCV 更换图片的背景色(附有完整代码)。
需要装一个包(很小,几十兆)
pip install opencv-python
Part.II Main_body
Chap.I 源码简析
基本配置:包括输入文件名、输出文件名、目标背景颜色(BGR)
filename_in=r'A:/OHanlon/Desktop/1017451354889.png'
filename_out=r'A:/OHanlon/Desktop/b.jpg'
color_target_bg=(255, 255, 255) #BGR
数据处理部分的流程大致如下:
- 将图片转换为灰度图片
- 图片二值化处理
- 腐蚀膨胀
- 遍历替换
调用 OpenCV 里面的主要的函数有
# 将图片转换为灰度图片
gray_img = cv2.cvtColor(new_img, cv2.COLOR_BGR2HSV)
# 腐蚀膨胀
erode = cv2.erode(binary_img, None, iterations=1)
dilate = cv2.dilate(erode, None, iterations=1)
Chap.II 效果展示
左边是原图,右边是转换后的图(好像只能将蓝底变为红底或白底)
Part.III 源码
整个源码如下:
import cv2
import numpy as np
def changeBackgroundColor():
filename_in=r'A:/OHanlon/Desktop/1017451354889.png'
filename_out=r'A:/OHanlon/Desktop/b.jpg'
color_target_bg=(255, 255, 255) #BGR
img = cv2.imread(filename_in, 1)
new_img = cv2.resize(img, None, fx=0.5, fy=0.5)
rows, cols, channels = new_img.shape
print(rows, cols, channels)
# 显示图像
cv2.imshow('source', new_img)
# 将图片转换为灰度图片
gray_img = cv2.cvtColor(new_img, cv2.COLOR_BGR2HSV)
# 图片二值化处理
low_value = np.array([90, 70, 70])
high_value = np.array([110, 255, 255])
binary_img = cv2.inRange(gray_img, low_value, high_value)
# 腐蚀膨胀
erode = cv2.erode(binary_img, None, iterations=1)
dilate = cv2.dilate(erode, None, iterations=1)
# cv2.imshow('dilate', dilate)
# 遍历替换
for i in range(rows):
for j in range(cols):
if dilate[i, j] == 255:
# 此处替换颜色,为BGR通道
new_img[i, j] = color_target_bg # (0, 0, 255)替换为红底 (255, 255, 255)替换为白底
cv2.imshow('result', new_img)
cv2.imwrite(filename_out,new_img)
# 窗口等待命令 0表示无限等待
cv2.waitKey(0)
cv2.destroyAllWindows()
# CALL function
changeBackgroundColor()