Python OpenCV – 覆盖透明的图像

前端之家收集整理的这篇文章主要介绍了Python OpenCV – 覆盖透明的图像前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我想要实现的是将具有透明度的图像放在另一个图像的顶部.像这样的东西:

enter image description here

我一直无法找到任何解决方案,所以我决定逐像素地计算得到的颜色.那个对我有用,但速度很慢.
我是OpenCV的新手,也是Python的新手.

这是我的代码,我提出:

  1. import numpy as np
  2. import cv2
  3. img1 = cv2.imread("img1.png",-1)
  4. img2 = cv2.imread("img2.png",-1) # this one has transparency
  5. h,w,depth = img2.shape
  6. result = np.zeros((h,3),np.uint8)
  7. for i in range(h):
  8. for j in range(w):
  9. color1 = img1[i,j]
  10. color2 = img2[i,j]
  11. alpha = color2[3] / 255.0
  12. new_color = [ (1 - alpha) * color1[0] + alpha * color2[0],(1 - alpha) * color1[1] + alpha * color2[1],(1 - alpha) * color1[2] + alpha * color2[2] ]
  13. result[i,j] = new_color
  14. cv2.imshow("result",result)
  15. cv2.waitKey(0)
  16. cv2.destroyAllWindows()

还有另一种方法吗?有些更快,更快?
谢谢.

最佳答案
答案:

  1. import numpy as np
  2. import cv2
  3. from time import time
  4. img1 = cv2.imread("./test_image/rgb.jpg",-1)
  5. img2 = cv2.imread("./test_image/rgba.png",c = img2.shape
  6. img1 = cv2.resize(img1,(w,h),interpolation = cv2.INTER_CUBIC)
  7. result = np.zeros((h,np.uint8)
  8. #slow
  9. st = time()
  10. for i in range(h):
  11. for j in range(w):
  12. color1 = img1[i,j] = new_color
  13. end = time() - st
  14. print(end)
  15. #fast
  16. st = time()
  17. alpha = img2[:,:,3] / 255.0
  18. result[:,0] = (1. - alpha) * img1[:,0] + alpha * img2[:,0]
  19. result[:,1] = (1. - alpha) * img1[:,1] + alpha * img2[:,1]
  20. result[:,2] = (1. - alpha) * img1[:,2] + alpha * img2[:,2]
  21. end = time() - st
  22. print(end)
  23. cv2.imshow("result",result)
  24. cv2.waitKey(0)
  25. cv2.destroyAllWindows()

猜你在找的Python相关文章