我想转换图像中的颜色,从而保留抗锯齿和透明背景。 初始图片是具有透明背景的png:
我使用以下代码将箭头从红色转换为绿色:
import numpy as np
import cv2
image = cv2.imread("C:/Temp/arr.png")
image = cv2.cvtColor(image, cv2.COLOR_BGR2BGRA)
cv2.imwrite('C:/Temp/source.png', image)
image[np.where((image == [0,0,255,255]).all(axis = 2))] = [0,255,0,255]
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGBA)
image[np.all(image == [255, 255, 255, 255], axis=2)] = [255, 255, 255, 0]
cv2.imwrite('C:/Temp/target.png', image)
但是箭头的对角线变得非常细:
我如何改善这种颜色转换?
答案 0 :(得分:1)
抗锯齿发生在您扔掉的alpha通道内。您无需执行cvtColor
,而是将Alpha通道保留在imread
中。
结果:
import numpy as np
import cv2
image = cv2.imread("arr.png", cv2.IMREAD_UNCHANGED)
b, g, r, a = cv2.split(image)
bgr = cv2.merge((b, g, r))
all_g = np.ones_like(bgr)
all_g[:, :] = (0,255,0)
bgr = np.where(bgr == (0,0,255), all_g, bgr)
image = cv2.merge((bgr, a))
cv2.imwrite('target.png', image)