2025年4月1日 星期二 乙巳(蛇)年 正月初二 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

opencv python 实现图片添加带透明的 logo

时间:11-24来源:作者:点击数:20
CDSY,CDSY.XYZ

图片叠加logo ffmpeg可以一条简单命令实现,  

  • ffmpeg -i D:\left\l0.jpg -i D:\logo\fst.png -lavfi [1]scale=160:-1[s1];[0][s1]overlay=20:50 -y D:\out\ooo_log3.mp4

但是Opencv实现有点麻烦, 特别是百度出来的一些文章, 各种mask ,bitwise 各种复杂操作

如下应该是个印度小哥的实现. 非常完美实现了功能.效果如下

黄色icon是带透明的 png图片, 如此完美叠加.

  • import cv2
  • def transparentOverlay(src, overlay, pos=(0, 0), scale=1):
  • """
  • :param src: Input Color Background Image
  • :param overlay: transparent Image (BGRA)
  • :param pos: position where the image to be blit.
  • :param scale : scale factor of transparent image.
  • :return: Resultant Image
  • """
  • overlay = cv2.resize(overlay, (0, 0), fx=scale, fy=scale)
  • h, w, _ = overlay.shape # Size of foreground
  • rows, cols, _ = src.shape # Size of background Image
  • y, x = pos[0], pos[1] # Position of foreground/overlay image
  • # loop over all pixels and apply the blending equation
  • for i in range(h):
  • for j in range(w):
  • if x + i >= rows or y + j >= cols:
  • continue
  • alpha = float(overlay[i][j][3] / 255.0) # read the alpha channel
  • src[x + i][y + j] = alpha * overlay[i][j][:3] + (1 - alpha) * src[x + i][y + j]
  • return src
  • def addImageWatermark(LogoImage,MainImage,opacity,pos=(10,100),):
  • opacity = opacity / 100
  • OriImg = cv2.imread(MainImage, -1)
  • waterImg = cv2.imread(LogoImage, -1)
  • tempImg = OriImg.copy()
  • print(tempImg.shape)
  • overlay = transparentOverlay(tempImg, waterImg, pos)
  • output = OriImg.copy()
  • # apply the overlay
  • cv2.addWeighted(overlay, opacity, output, 1 - opacity, 0, output)
  • cv2.imshow('Life2Coding', output)
  • cv2.waitKey(0)
  • cv2.destroyAllWindows()
  • if __name__ == '__main__':
  • #addImageWatermark(r'D:\logo\face.png',r'D:\img\55.jpg',100,(10,100))
  • addImageWatermark(r'D:\logo\fst.png',r'D:\img\55.jpg',100,(0,100))
CDSY,CDSY.XYZ
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐