学习来自【OpenCv】利用roi 掩模 将一张图片添加到另一张上
任务描述:提取图片A的 mask 区域,并粘贴到图片B上
A 图
A 图的 mask 标签
B 图
结果
下面看看代码流程
import cv2
import numpy as np
from os.path import join
from os import listdir
rootpath = "/home/bryant/datasets/"
img1 = cv2.imread(join(rootpath, "images", "00000.jpg")) # A 图
img2 = cv2.imread(join(rootpath, "matting", "00000.jpg")) # A 图 mask
img3 = cv2.imread("animal_world_70223.jpg") # B 图
h, w, c = img1.shape
img1 = cv2.resize(img1, (w//2, h//2))
img2 = cv2.resize(img2, (w//2, h//2))
img3 = cv2.resize(img3, (w//2, h//2))
img2not = cv2.bitwise_not(img2)
img2_gray = cv2.cvtColor(img2not, cv2.COLOR_BGR2GRAY)
ret, mat = cv2.threshold(img2_gray, 170, 255, cv2.THRESH_BINARY)
cv2.imshow("1", mat) # 图 1 mask 黑白颠倒
fg1 = cv2.bitwise_and(img3, img3, mask=mat)
cv2.imshow("2", fg1) # 图 2,仅输出 mask 非零区域的与
mat2 = cv2.bitwise_not(mat)
cv2.imshow('3', mat2) # 图 3,mask 黑白颠倒回来
fg2 = cv2.bitwise_and(img1, img1, mask=mat2)
cv2.imshow('4', fg2) # 图 4,仅输出 mask 非零区域的与
dst = cv2.add(fg1, fg2) # 图 2 图 4 结合
cv2.imshow('dst', dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
图 1
图 2
图 3
图 4
结果
mask,图像掩膜,可选参数,为8位单通道的灰度图像,用于指定要更改的输出图像数组的元素,即输出图像像素只有mask对应位置元素不为0的部分才输出,否则该位置像素的所有通道分量都设置为0
mask = cv2.imread("mask.jpg")
gray = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
_, new_mask = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY)
non_zero_indices = np.nonzero(new_mask)
x_ind = non_zero_indices[1]
y_ind = non_zero_indices[0]
x_min, x_max = np.min(x_ind), np.max(x_ind)
y_min, y_max = np.min(y_ind), np.max(y_ind)
bbox = [x_min, x_max, y_min, y_max]