python - 使用 Numpy 或 OpenCV 将图像中的剪切内容复制到新图像

标签 python numpy opencv

是否可以使用 Python 中的 OpenCV 或 Numpy 仅复制图像中的特定区域并将其粘贴到另一个图像?

假设我有一个 RGB 图像和一个图像的灰度蒙版。 (两者尺寸相同)

enter image description here enter image description here

是否可以仅将 mask 像素重叠到新图像的特定部分的船只复制?

enter image description here

这是我尝试过的代码。

image1 = cv2.imread("boat.png")
mask = cv2.imread("boat_mask.png")
image2 = cv2.imread("sea.png")
width, height = image1.shape
image2[y:y+height,x:x+width] = image1[mask==255]

这不起作用,因为 image1[mask==255] 不再具有 2d 形状。

解决方案:

image2_cutout = image2[y:y+height,x:x+width]
image2_cutout[mask==255] = image1[mask==255]
image2[y:y+height,x:x+width] = image2_cutout

最佳答案

这里是:

import cv2


image1 = cv2.imread("data/boat.png")
_, mask = cv2.threshold(cv2.cvtColor(cv2.imread("data/masked_boat.png"), cv2.COLOR_BGR2GRAY), 120, 255, cv2.THRESH_BINARY)
image2 = cv2.imread("data/sea.jpg")
width, height, _ = image1.shape
y = 300
x = 300

masked_normalized = cv2.bitwise_and(image1, image1, mask=mask)

cut_from_bg = image2[x:x+width, y:y+height]
img1_bg = cv2.bitwise_and(cut_from_bg, cut_from_bg, mask=cv2.bitwise_not(mask))

dst = cv2.add(img1_bg, masked_normalized)

image2[x:width + x, y:height + y] = dst
cv2.imshow("sea_with_boat", image2)

cv2.waitKey(0)
cv2.destroyAllWindows()

我在这里做的第一件事是获取船的mask,并使用cv2.bitwise_and获得船的真实蒙版图像。然后我在想要放置船的地方切出了一部分海,并在这里切出了船的形状。然后我使用cv2.add组合蒙版船图像和剪切的海洋图像,然后我将这部分图像放在原始海洋图像上。

关于python - 使用 Numpy 或 OpenCV 将图像中的剪切内容复制到新图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67209425/

相关文章:

python - Sqlite3 INSERT查询错误?

python - Keras 拟合模型 : TypeError: unhashable type: 'numpy.ndarray'

python - 从较粗糙的栅格中提取图像像素值

python - 在 numpy 数组中从末尾切片可变距离的更多 Pythonic 方法

python - 魔法函数timeit

Python:在二叉搜索树中寻找共同祖先的递归

python - OpenCV 中的图像转换

c++ - 当程序在两者之间进入休眠状态时,OpenCV 函数 cv::remap() 的执行时间更长

python - Spark 使用 where 条件更新数据帧

python - 在opencv SGBM中,当我使名为numDisparities的参数变大时,为什么视差图的左侧部分变暗?