我尝试使用OpenCV和Python覆盖随机图像(自然场景图像应该覆盖符号图像)。它们可以在大小、文件扩展名和频道数量上有所不同(我想可能还有更多)。所以我要根据自然场景图像的大小调整标牌图像的大小,并将它们放在后者上。在
我已经实现了fireant在这里找到的代码:overlay a smaller image on a larger image python OpenCv
但它只适用于4个通道的图像。在
使用cv2.addWeighted()总是将较大的图像(场景图像)裁剪为较小图像(符号图像)的大小。有人知道怎么做吗?非常感谢帮助。在
编辑:请参阅下面的预期输出。起初,逃生路线标志和背景是分开的图像。
这是我的代码,它正在工作,但由于我的许多图像似乎只有3个通道,我想让它也为那些工作。在
import cv2
import time
import math
import os
pathSigns = "/home/moritz/Schreibtisch/Signs"
pathScenes = "/home/moritz/Schreibtisch/Scenes"
i = 0
for fSigns in os.listdir(pathSigns):
fSigns = os.path.join(pathSigns, fSigns)
s_img = cv2.imread(fSigns, -1)
for fScenes in os.listdir(pathScenes):
try:
l_img = cv2.imread(os.path.join(pathScenes, fScenes))
l_height, l_width, l_channels = l_img.shape
TARGET_PIXEL_AREA = (l_height * l_width) * 0.05
ratio = float(s_img.shape[1]) / float(s_img.shape[0])
s_new_h = int(math.sqrt(TARGET_PIXEL_AREA / ratio) + 0.5)
s_new_w = int((s_new_h * ratio) + 0.5)
s_img = cv2.resize(s_img,(s_new_w, s_new_h))
x_offset=y_offset=50
# l_img[y_offset:y_offset+s_img.shape[0],
x_offset:x_offset+s_img.shape[1]] = s_img
y1, y2 = y_offset, y_offset + s_img.shape[0]
x1, x2 = x_offset, x_offset + s_img.shape[1]
height, width, channels = s_img.shape
if channels <= 3:
alpha_s = s_img[:, :, 2] / 255.0
alpha_l = 1.0 - alpha_s
else:
alpha_s = s_img[:, :, 3] / 255.0
alpha_l = 1.0 - alpha_s
for c in range(0, 3):
l_img[y1:y2, x1:x2, c] = (alpha_s * s_img[:, :, c] +
alpha_l * l_img[y1:y2, x1:x2, c])
fResult = "/home/moritz/Schreibtisch/results/data_" + str(i) +
".png"
i += 1
cv2.imwrite(fResult, l_img)
except IndexError:
pass
多亏了@DanMašek hint和How to crop or remove white background from an image,我找到了一个解决方案。下面的代码将首先从较小的图像中删除白色背景,然后将所有图像设置为4个通道,然后用较小的图像覆盖较大的图像。对我有用。在
相关问题 更多 >
编程相关推荐