我的目標是使用 Python 將前景物件插入到背景影像中的特定位置(例如,在中心部分、左下部分等)。
獲取前景(周圍像素設定為零):
# Read the image
img = cv2.imread('/content/foreground.jpg')/255.0
foreground = img.copy()
foreground[foreground>=0.9]=0
plt.axis('off')
plt.imshow(foreground)
plt.show()
為這個前景物件創建一個蒙版:
def getForegroundMask(foreground):
mask_new = foreground.copy()[:,:,0]
mask_new[mask_new>0] = 1
return mask_new
mask_new = getForegroundMask(foreground)
plt.imshow(mask_new)
plt.axis('off')
plt.show()
獲取背景:
background = cv2.imread('/content/background.png')/255.0
plt.imshow(background)
plt.axis('off')
plt.show()
用背景組合物件:
def compose(foreground, mask, background):
# resize background
background = transform.resize(background, foreground.shape[:2])
# Subtract the foreground area from the background
background = background*(1 - mask.reshape(foreground.shape[0], foreground.shape[1], 1))
# Finally, add the foreground
composed_image = background foreground
return composed_image
結果,前景物件采用了背景影像的全尺寸,但我想要的是自定義并將此物件插入不同的部分和不同的大小。我怎么能做到?

uj5u.com熱心網友回復:
為此,您可以使用切片。假設您要將前景放在背景上的 (x, y) 坐標處。
h, w = foreground.shape[:2]
# Subtract the foreground area from the background
background[y:y h, x:x w] *= (1 - mask.reshape(foreground.shape[0], foreground.shape[1], 1))
background[y:y h, x:x w] = foreground
return background
y h在這里,請確保x w不要超過背景尺寸。
uj5u.com熱心網友回復:
Rahul Kedia 的回答構成了該解決方案的基礎。但是,您不需要從背景中減去蒙版區域以稍后添加前景。
您只需提及您感興趣的位置即可覆寫它。在以下示例中,我從原點放置前景影像。
background = cv2.imread(background_image_path, 1)
foreground = cv2.imread(foreground_image_path, 1)
f_ht, f_wd, _ = foreground.shape
background[0:f_ht, 0:f_wd] = foreground
uj5u.com熱心網友回復:
直線前進少于 25 行。我們不使用 matplotlib 庫。
#!/usr/bin/python3.9.2
import cv2
import numpy as np
img1 = cv2.imread('ralph.jpg')
overlay_img1 = np.ones(img1.shape,np.uint8)*255
img2 = cv2.imread('mainlogo.png')
rows,cols,channels = img2.shape
overlay_img1[450:rows 450, 450:cols 450 ] = img2
img2gray = cv2.cvtColor(overlay_img1,cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img2gray,220,55,cv2.THRESH_BINARY_INV)
mask_inv = cv2.bitwise_not(mask)
temp1 = cv2.bitwise_and(img1,img1,mask = mask_inv)
temp2 = cv2.bitwise_and(overlay_img1,overlay_img1, mask = mask)
result = cv2.add(temp1,temp2)
cv2.imshow("Result",result)
cv2.waitKey(0)
cv2.destroyAllWindows()
輸出疊加:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/462352.html
