簡體   English   中英

如何使用OpenCV將圖像的一部分復制到另一個?

[英]how to copy a part of image to another with OpenCV?

我有一個預測人臉分割的模型。

圖片描述

但是不幸的是,該模型沒有經過訓練來預測面部的頭發。 所以現在我將以上圖像作為numpy數組。 是否可以將原始照片中的頭發(左側的頭發)添加到預測蒙版(中間)或直接添加到結果預測中(右側的頭發)?

基本上,我只需要處理原始圖像,以從預測蒙版上方的頭部得到一點點,然后將其添加到預測中,這樣至少可以在結果中保留一部分頭發。

用於創建上圖的代碼:

fn = "images/beard.jpg"
im = cv2.cvtColor(cv2.imread(fn), cv2.COLOR_BGR2RGB)
im = auto_downscaling(im)

# vgg_preprocess: output BGR channel w/ mean substracted.
inp_im = vgg_preprocess(im)

# Predicting the face segmentation
out = model.predict([inp_im])

out_resized = cv2.resize(np.squeeze(out), (im.shape[1],im.shape[0]))
out_resized_clipped = np.clip(out_resized.argmax(axis=2), 0, 1).astype(np.float64)
mask = cv2.GaussianBlur(out_resized_clipped, (7,7), 6)


plt.figure(figsize=(12,6))
plt.subplot("131")
plt.axis('off')
plt.imshow(im)
plt.subplot("132")
plt.axis('off')
plt.imshow(out_resized_clipped, cmap='gray')
plt.subplot("133")
plt.axis('off')
plt.imshow((mask[:,:,np.newaxis]*im.astype(np.float64)).astype(np.uint8))
plt.show()

為了演示您想要什么,我對此進行了測試。 首先,我創建一些函數來根據輸入創建相似大小的圖像。

import cv2
import numpy as np

def resize(img, dim=(300, 300)):
    # perform the actual resizing of the image and show it
    frame = cv2.resize(img, dim, interpolation=cv2.INTER_AREA)
    return frame

然后分別閱讀和調整圖像大小

img1 = resize(cv2.imread('img1.png'))
img2 = resize(cv2.imread('img2.png'))
dst = cv2.addWeighted(img1,0.7,img2,0.3,0)

cv2.addWeighted函數將幫助我獲得結果。 然后您可以根據需要執行輸出

cv2.imwrite('out.png', dst)

因此,將相同的原理應用於您的代碼將是類似的事情。 我看到那里有類似尺寸的圖像。

fn = "images/beard.jpg"
im = cv2.cvtColor(cv2.imread(fn), cv2.COLOR_BGR2RGB)
im = auto_downscaling(im)

# vgg_preprocess: output BGR channel w/ mean substracted.
inp_im = vgg_preprocess(im)

# Predicting the face segmentation
out = model.predict([inp_im])

out_resized = cv2.resize(np.squeeze(out), (im.shape[1],im.shape[0]))
out_resized_clipped = np.clip(out_resized.argmax(axis=2), 0, 1).astype(np.float64)
out_resized_clipped = cv2.GaussianBlur(out_resized_clipped, (7,7), 6)

mask = cv2.addWeighted(out_resized, 0.7, out_resized_clipped,0.3,0)
mask = cv2.GaussianBlur(out_resized_clipped, (7,7), 6)

plt.figure(figsize=(12,6))
plt.subplot("131")
plt.axis('off')
plt.imshow(im)
plt.subplot("132")
plt.axis('off')
plt.imshow(out_resized_clipped, cmap='gray')
plt.subplot("133")
plt.axis('off')
plt.imshow((mask[:,:,np.newaxis]*im.astype(np.float64)).astype(np.uint8))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM