前言
在处理图像中我们有时候需要将某张图像的背景替换掉,或者将某张图像中指定的RGB颜色替换成另外的一种RGB。为此,我在这里提供两种实现方案供大家选用。
遍历法
使用遍历法替换掉图像中的指定RGB。
流程:
- 读取图像
- 转为np.asarray
- 构建for循环遍历RGB三层值
- find(指定值) == 修改值
- 输出图像
def replace_color(img, old_rgb, new_rgb):
# 通过遍历颜色替换程序
img_arr = np.asarray(img, dtype=np.double)
new_arr = img_arr.copy()
for i in range(img_arr.shape[1]):
for j in range(img_arr.shape[0]):
if (img_arr[j][i] == old_rgb)[0] == True:
new_arr[j][i] = new_rgb
return np.asarray(new_arr, dtype=np.uint8)
矩阵法
RGB图像是由三层RGB矩阵组合而成,我们在替换指定的RGB时候可以将原图像的三层RGB分离出来,对每层矩阵中的值搜索替换即可。
流程:
- 读取图像
- 分离原图RGB三层空间
- 对分离出来的三层空间编码
- 索引并替换颜色
- 组合替换后的三层空间成完整的图
def replace_color(img, old_rgb, new_rgb):
# 通过矩阵操作颜色替换程序
img_arr = np.asarray(img, dtype=np.double)
# 分离通道
r_img = img_arr[:, :, 0].copy()
g_img = img_arr[:, :, 1].copy()
b_img = img_arr[:, :, 2].copy()
# 编码
img = r_img * 256 * 256 + g_img * 256 + b_img
old_color = old_rgb[0] * 256 * 256 + old_rgb[1] * 256 + old_rgb[2]
# 索引并替换颜色
r_img[img == old_color] = new_rgb[0]
g_img[img == old_color] = new_rgb[1]
b_img[img == old_color] = new_rgb[2]
# 合并通道
new_img = np.array([r_img, g_img, b_img], dtype=np.uint8)
# 将数据转换为图像数据(h,w,c)
new_img = new_img.transpose(1, 2, 0)
return new_img
结果
这两种方法都可以完成替换RGB区域的任务,在这里我推荐使用矩阵法(二者耗时相比较矩阵法耗时少)