问题:前段时间使用python3+opencv2给博客添加了图片上传添加水印 功能,但是水印固定为白色,当给白色背景图片添加水印后完全看不出来。
思路:判断不同背景色像素 然后选择不同颜色的水印,所以需要取出需要添加水印图片位置的颜色信息进行判断
实例代码demo如下:
def addWaterMark(self,path):
img = cv.imread(path)
font = cv.FONT_HERSHEY_COMPLEX_SMALL
bgr = img[(int(img.shape[0]*0.5), img.shape[1]-15)]
if all(bgr==np.array([255, 255,255])):
cv.putText(img, 'yy123.ink', (int(img.shape[1]*0.5), img.shape[0]-15), font, 0.8, (51, 204, 153),2)
else:
cv.putText(img, 'yy123.ink', (int(img.shape[1] * 0.5), img.shape[0] - 15), font, 0.8, (255, 255, 255), 2)
# 保存添加文字后的图片
cv.imwrite('D:/images/223.jpg', img)
坑:The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
nparray矩阵直接比较相等报错:
if bgr==np.array([255, 255,255]):
因为返回的是 :[True True True]
错误提示使用any和all,
显然any() 表示只要有一个True 就返回 True,
all()表示所有元素为True才会返回True, 否则返回False.
所以改成如下:
if all(bgr==np.array([255, 255,255])):