【python】Paste Mask

学习来自【OpenCv】利用roi 掩模 将一张图片添加到另一张上

任务描述:提取图片A的 mask 区域,并粘贴到图片B上

文章目录

  • [1 代码实现](#1 代码实现)
  • [2 结果展示](#2 结果展示)
  • [3 涉及到的库](#3 涉及到的库)
  • [附录------获取 mask 的边界框](#附录——获取 mask 的边界框)

1 代码实现

A 图

A 图的 mask 标签

B 图

结果

下面看看代码流程

py 复制代码
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()

2 结果展示

图 1

图 2

图 3

图 4

结果

3 涉及到的库

cv2.bitwise_not

cv2.bitwise_and

mask,图像掩膜,可选参数,为8位单通道的灰度图像,用于指定要更改的输出图像数组的元素,即输出图像像素只有mask对应位置元素不为0的部分才输出,否则该位置像素的所有通道分量都设置为0

cv2.add

附录------获取 mask 的边界框

py 复制代码
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]
相关推荐
代码讲故事15 分钟前
多种方法实现golang中实现对http的响应内容生成图片
开发语言·chrome·http·golang·图片·快照·截图
天天爱吃肉821820 分钟前
ZigBee通信技术全解析:从协议栈到底层实现,全方位解读物联网核心无线技术
python·嵌入式硬件·物联网·servlet
虾球xz1 小时前
CppCon 2018 学习:EFFECTIVE REPLACEMENT OF DYNAMIC POLYMORPHISM WITH std::variant
开发语言·c++·学习
Allen_LVyingbo1 小时前
Python常用医疗AI库以及案例解析(2025年版、上)
开发语言·人工智能·python·学习·健康医疗
小哈龙1 小时前
裸仓库 + Git Bash 搭建 本地 Git 服务端与客户端
开发语言·git·bash
智能砖头1 小时前
LangChain 与 LlamaIndex 深度对比与选型指南
人工智能·python
G探险者1 小时前
《如何在 Spring 中实现 MQ 消息的自动重连:监听与发送双通道策略》
java·开发语言·rpc
weixin_437398212 小时前
转Go学习笔记
linux·服务器·开发语言·后端·架构·golang
StrongerIrene2 小时前
rs build 的process.env的值undefined解决方案
开发语言·javascript·ecmascript
风逸hhh2 小时前
python打卡day58@浙大疏锦行
开发语言·python