【问题标题】:Error when overlaying two images in OpenCV and or PIL在 OpenCV 和/或 PIL 中叠加两个图像时出错
【发布时间】:2018-10-14 07:13:19
【问题描述】:

我尝试在 openCV 和 PIL 中叠加 openCV 中的两个图像,但无济于事。我正在使用np.zeros 的1000x1000x3 数组作为背景(又名黑色背景)和this 显示器的随机图像,但由于某种我不知道的原因,我真的无法让它工作。

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

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

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

base_temp = cv2.convertScaleAbs(self.base)   #Convert to uint8 for cvtColor
base_temp = cv2.cvtColor(base_temp, cv2.COLOR_BGR2RGB)   #PIL uses RGB and OpenCV uses BGR
base_temp = Image.fromarray(base_temp)    #Convert to PIL Image
foreground_temp = cv2.cvtColor(cv2.convertScaleAbs(self.last_img), cv2.COLOR_BGR2RGB)
foreground_temp = Image.fromarray(foreground_temp)
base_temp.paste(foreground_temp, offset)

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

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

【问题讨论】:

  • 你期望得到什么样的结果图像?
  • @DmitriiZ。 foreground_temp 就在base_temp 的中间——或者至少根据提供的偏移量粘贴在base_temp 的中间

标签: python opencv python-imaging-library cv2


【解决方案1】:

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

所以解决方案是使用正确的类型创建您的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')

【讨论】:

  • 感谢您的回复,但我在 PIL 示例中的 cv2.convertScaleAbs 行中这样做了——这就是它存在的原因。
  • 我指的是你的第一个例子。
  • 我尝试了您的解决方案,但最终得到的图像与我上面链接的结果非常相似——黑屏带有一条奇怪的线条和几个杂散像素。在这一点上我真的很难过。
  • 我只能怀疑您的安装是“不满意”,并且您重新安装。我的代码是直截了当的,如图所示并经过测试。
  • 好吧,该死的。我在ubuntu上试过这个,效果很好,所以我会接受你的回答。即使它仍然相对“新鲜”,为什么安装可能会以这种方式结束?
猜你喜欢
  • 1970-01-01
  • 2019-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多