【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]
相关推荐
AI探索者7 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者7 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh9 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅9 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽10 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时14 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿16 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi1 天前
Chapter 2 - Python中的变量和简单的数据类型
python