【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]
相关推荐
清弦墨客13 分钟前
【蓝桥杯】43697.机器人塔
python·蓝桥杯·程序算法
※DX3906※1 小时前
cpp实战项目—string类的模拟实现
开发语言·c++
wjs20241 小时前
Nginx 安装配置指南
开发语言
美味小鱼1 小时前
实践Rust:编写一个猜数字游戏
开发语言·游戏·rust
Dr.勿忘2 小时前
C#面试常考随笔8:using关键字有哪些用法?
开发语言·unity·面试·c#·游戏引擎
RZer2 小时前
Hypium+python鸿蒙原生自动化安装配置
python·自动化·harmonyos
dal118网工任子仪2 小时前
92,[8] 攻防世界 web Web_php_wrong_nginx_config
开发语言·php
wjs20242 小时前
SQLite Update 语句详解
开发语言
加油,旭杏2 小时前
【go语言】接口
开发语言·后端·golang
xianwu5433 小时前
反向代理模块jmh
开发语言·网络·数据库·c++·mysql