从具有固定背景的图像中删除背景

2024-03-29 14:58:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从一个带有单个自由落体的图像中删除固定背景。图像有一个单独的自由落体对象,中间有一个圆形背景的白色背景。

Test cases worked

下面是我执行上述任务的代码。我使用了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)

我的代码可以很好地处理上述数据集,但无法处理以下图像数据:

Test Case that doesn't work

如果对象的颜色为灰色纹理,则它也不起作用。我认为,当对象的像素分布均匀且与背景(即圆形面片)不同时,效果很好

有没有其他最好的方法来完成这项任务,这样它就可以从物体的中空区域减去背景,而不必减去物体的某些部分


Tags: path对象代码图像importforoscv2
1条回答
网友
1楼 · 发布于 2024-03-29 14:58:50

使用下面的代码,我认为它现在可以工作了

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,0] #it will replace background with black color, you can change it for example to [255,0,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)

相关问题 更多 >