在OpenCV和/或PIL中叠加两个图像时出错

时间:2018-10-14 07:13:19

标签: python opencv python-imaging-library cv2

我已经尝试在openCV和PIL中在openCV中覆盖两个图像,但无济于事。我正在使用1000x1000x3的{​​{1}}数组作为背景(又称黑色背景)和显示器的this随机图像,但是我确实无法使其正常工作我不知道的某些原因。

仅尝试使用OpenCV:(result(如果您注意的话,您会在中间看到几条奇怪的线和点))

np.zeros

尝试使用PIL :(结果实际上与OpenCV版本相同)

base_temp = np.zeros((1000,1000,3))
foreground_temp = cv2.imread('exampleImageThatILinkedAbove.png')

base_temp[offset_y:offset_y+foreground_temp.shape[0], offset_x:offset_x+foreground_temp.shape[1]] = foreground_temp

如果有帮助,我正在Windows 10上使用python3.5和OpenCV3.4。

我希望 避免任何需要保存cv2图像,然后将其重新加载到另一个模块中以进行转换的解决方案,但是如果不可避免的话,也可以。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

如果检查base_temp的类型,您将看到它是float64,当您尝试将其另存为JPEG时需要使用无符号8位值,这将给您带来麻烦。

因此解决方案是使用正确的类型创建base_temp图像:

base_temp = np.zeros((1000,1000,3), dtype=np.uint8)    

完整的代码和结果如下:

import cv2
import numpy as np
from PIL import Image

# Make black background - not square, so it shows up problems with swapped dimensions
base_temp=np.zeros((768,1024,3),dtype=np.uint8)
foreground_temp=cv2.imread('monitor.png')

# Paste with different x and y offsets so it is clear when indices are swapped
offset_y=80
offset_x=40
base_temp[offset_y:offset_y+foreground_temp.shape[0], offset_x:offset_x+foreground_temp.shape[1]] = foreground_temp

Image.fromarray(base_temp).save('result.png')

enter image description here