将两幅图添加起来,构成一幅新的图像,并尝试将一个PNG的透明背景转换为特定的颜色。
生成纯背景
以下代码生成一个纯色背景JPG,颜色为照片底板的蓝(R:60 G:140 B:220
)。在用OpenCV
创建图像时,颜色按BGR
。
import cv2
import numpy as np
def create_blank(width, height, rgb_color=(60, 140, 220)):
"""Create new image(numpy array) filled with certain color in RGB"""
# Create black blank image
image = np.zeros((height, width, 3), np.uint8)
# Since OpenCV uses BGR, convert the color first
color = tuple(reversed(rgb_color))
# Fill image with color
image[:] = color
return image
img = cv2.imread('dog.png')
(rows, cols) = img.shape[:2]
blank = create_blank(cols, rows)
cv2.imwrite('blue.jpg', blank)
两个图像相加
两个图像大小相同的情况下,可以通过矩阵叠加方法——OpenCV Python中,为cv2.add
,合并在一起,代码如下:
import cv2
img1 = cv2.imread('dog.png')
img2 = cv2.imread('blue.jpg')
# Add 2 images
img_dst = cv2.add(img1, img2)
# Display the processed images
cv2.imshow('img', img_dst )
cv2.imwrite('add.jpg', img_dst)
# Wait for a key press and then close the windows
cv2.waitKey(0)
cv2.destroyAllWindows()
显然,这是矩阵个元素数值的相加,那么,假如要把透明背景用别的颜色替换,而不是这样相加,又该“如何应对”?
透明色转换
读入一个有透明背景的png
图片,然后我们会发现,它的α
通道是0。
import cv2
# Read a png with alpha channel
img = cv2.imread('dog.png', cv2.IMREAD_UNCHANGED)
cv2.imshow('img', img)
cv2.imwrite('dog.png', img)
# Wait for a key press and then close the windows
cv2.waitKey(0)
cv2.destroyAllWindows()
对于图像的透明部分,其值为[0,0,0,0],那么我们可以将该透明部分修改成对应的颜色,具体见函数transparent2bgra_color
。
import cv2
import numpy as np
def transparent2bgra_color(img, bgra_color=(255, 255, 255, 255)):
# Avoid the side-effect
res = img.copy()
res[img[:, :, 3] == 0] = bgra_color
return res
# Read the png image with alpha channel
origin_img = cv2.imread('dog.png', cv2.IMREAD_UNCHANGED)
dst_img = transparent2bgra_color(origin_img, bgra_color=(220, 140, 60, 255))
black_dog = transparent2bgra_color(origin_img, bgra_color=(0, 0, 0, 255))
cv2.imshow('Origin', origin_img)
cv2.imshow('Converted', dst_img)
cv2.imshow('Black', black_dog)
cv2.imwrite('new_dog.png', dst_img)
cv2.imwrite('black_dog.png', black_dog)
# Wait for a key press and then close the windows
cv2.waitKey(0)
cv2.destroyAllWindows()
Origin:
Converted:
Black: