Python cv2 & numpy - 合并两个图像

Python cv2 & numpy - combining two images

我有一张船的图像,我需要根据传感器的值对各个区域进行着色。到目前为止,我已经创建了两个 .png 格式的独立区域,我想同时显示它们,将它们放在基本的船图像上。

我的代码:

import cv2
import numpy as np
from PIL import Image
import time

bg = cv2.imread("boat.png")
#RGB = np.zeros((2178, 2904, 3), dtype=np.uint8)
#zone11
zone11 = cv2.imread(r'C:\Users\Lenovo\Anaconda3\Programy\Obszary.png')
#zone12
zone12 = cv2.imread(r'C:\Users\Lenovo\Anaconda3\Programy\Obszary.png')

combined = np.maximum.reduce([zone11, zone12])
cv2.imwrite('combined.png',combined)
cv2.imshow('combined',combined)
#cv2.imshow('bg',bg)
cv2.waitKey(5)
time.sleep(5)
cv2.destroyAllWindows();

问题是 np.maximum.reduce 在一张图片上给了我两个区域,但是背景是黑色的,它给了我内核错误...

没有黑色背景如何保存?以及如何将它们放在基本的船图像上?将来区域将每 1 秒显示一次,并且它们在每个序列中都会不同,我如何将区域粘贴到一个序列中并在下一个序列之前取消粘贴?

我将不胜感激,我对图形和 python 还很陌生。

Imgur 图片: 1. 船 https://imgur.com/cA9slkZ 2.合并https://imgur.com/lKxLxgN 3. 12 区 https://imgur.com/zIVgoZh 4. 11 区 https://imgur.com/PMUGWW6

为了合并区域,您需要在每个点上取最亮的像素,这将在黑色背景上为您提供合并区域:

# "zones" will contain all the zones combined together by choosing the brightest pixel at each point
zones = np.maximum.reduce([zone11, zone12])

现在我们要找到任何颜色通道不为零的所有位置,即所有非黑色区域。

# "alpha" will be True where the zones are activated
alpha = np.any(zones>0, axis=2)

然后,对于最终结果,您要选择它们活跃的组合区域,以及其他地方的船:

# For the final result, pick the zones at locations where they contain stuff, and the boat anywhere else
res = np.where(alpha[...,np.newaxis], zones, boat)

# Save result to disk
cv2.imwrite('result.png', res)

关于每秒都做这一切,您只需复制在程序开始时在循环外加载的船图像,创建区域并将它们放在副本上:

# Load boat once at startup
boat_orig = cv2.imread("boat.png")

# Main loop
while not sunk:
    boat = boat_orig.copy()
    zones = np.maximum.reduce([zone11, zone12])
    alpha = np.any(zones>0, axis=2)
    res = np.where(alpha[...,np.newaxis], zones, boat)

内循环中的那 4 行 运行 在我的机器上大约 400 毫秒,其中 200 毫秒是行:

alpha = np.any(zones>0, axis=2)

您可能会发现可以更改为:

alpha = zones[...,2]

因为红色通道中总会有一些东西(假设您的区域是橙红色),这会将 200 毫秒减少到 1 毫秒以下。