问题描述
我正在尝试使用单个自由落体对象从图像中删除固定背景。该图像有一个自由下落的物体,它的背景为白色,中间有一个圆形补丁。
下面是我完成上述任务的代码。我已经使用OpenCV BackgroundSubtractorKNN和BackgroundSubtractormog2算法来完成此任务。左图应作为输入,代码应生成右图作为输出。
import numpy as np
import cv2
import sys
import os
#backgroundSubtractor = cv2.createBackgroundSubtractormog2()
backgroundSubtractor = cv2.createBackgroundSubtractorKNN()
# apply the algorithm for background images using learning rate > 0
for i in range(1,16):
bgImageFile = "background/BG.png"
print("opening background",bgImageFile)
bg = cv2.imread(bgImageFile)
backgroundSubtractor.apply(bg,learningRate=0.5)
# apply the algorithm for detection image using learning rate 0
dirc = os.getcwd()
filepath = os.path.join(dirc,'data')
if not os.path.exists('saved_bgRemoved'):
os.makedirs('saved_bgRemoved')
for file in os.listdir(filepath):
stillFrame = cv2.imread(os.path.join(filepath,file))
fgmask = backgroundSubtractor.apply(stillFrame,learningRate=0)
bgImg = cv2.bitwise_and(stillFrame,stillFrame,mask=fgmask)
# show both images
cv2.imshow("original",stillFrame)
cv2.imshow("mask",fgmask)
cv2.imshow("Cut Image",bgImg)
cv2.waitKey()
cv2.destroyAllWindows()
cv2.imwrite(os.path.join('saved_bgRemoved',file),bgImg)
我的代码与上面的数据集配合得很好,但是不能与下面的图像数据一起使用:
如果对象以灰色纹理上色,也将不起作用。我认为当对象的像素分布均匀且与背景(即圆形补丁)不同时,效果很好。
还有其他最佳方法可以完成此任务,以便它甚至可以从对象的空心区域中减去背景,而无需减去对象的一部分吗?
解决方法
使用下面的代码,我认为现在可以使用
import cv2,os
def remove_bg(bg_path,im_path):
bg = cv2.imread(bg_path)
im = cv2.imread(im_path)
row,col,_ = im.shape
for i in range(0,row):
for j in range(0,col):
if ( bg[i][j][0] == im[i][j][0] and bg[i][j][1] == im[i][j][1] and bg[i][j][2] == im[i][j][2] ):
im[i][j] = [0,0] #it will replace background with black color,you can change it for example to [255,0] to replace it with red
return(im)
directory,_=os.path.split(__file__)
bg_path = directory + "\\background.png"
im_path = directory + "\\data6.png"
result = remove_bg(bg_path,im_path)
cv2.imshow("result",result)
cv2.waitKey()
cv2.imwrite(directory + "\\Result.png",result)