加载库并读取图像
from __future__ import division
import cv2
import numpy as np
guy_img = cv2.imread('path')
target_img = cv2.imread('path')
获取该人(每个非零像素)和目标蒙版(粉红色区域)的边界框。
a = np.where(guy_img > 0)
b = np.where(target_img == 129) # picked one of the channels in your image
bbox_guy = np.min(a[0]), np.max(a[0]), np.min(a[1]), np.max(a[1])
bbox_mask = np.min(b[0]), np.max(b[0]), np.min(b[1]), np.max(b[1])
请注意,当我加载目标图像时,值与您提供的值不同。图像边缘还有一些白色像素。这可能只是由于图像被上传到 imgur 并下载。如果你的值是正确的并且你的图像的其余部分是完全黑色的,除了粉红色区域你可以得到所有非零像素,就像我用np.where(target_img > 0)
.
现在只获取 guy 和 mask 区域的值
guy = guy_img[bbox_guy[0]:bbox_guy[1], bbox_guy[2]:bbox_guy[3],:]
target = target_img[bbox_mask[0]:bbox_mask[1], bbox_mask[2]:bbox_mask[3],:]
将这个人的大小调整为与面具相同的比例/形状
guy_h, guy_w, _ = guy.shape
mask_h, mask_w, _ = target.shape
fy = mask_h / guy_h
fx = mask_w / guy_w
scaled_guy = cv2.resize(guy, (0,0), fx=fx,fy=fy)
用家伙图像值重新分配目标图像的蒙版区域
for i, row in enumerate(range(bbox_mask[0], bbox_mask[1])):
for j, col in enumerate(range(bbox_mask[2], bbox_mask[3])):
target_img[row,col,:] = scaled_guy[i,j,:]
cv2.imshow('', target_img)
cv2.waitKey(0)