如何去除嘈杂图像的背景并提取透明对象?

问题描述

我有一个无法解决的图像处理问题。我有一组375张像下面的图像(1)。我正在尝试删除背景,以便进行“背景减法”(或“前景提取”),仅在纯背景(黑色/白色/ ...)上获得废物。

(1) Image example

我尝试了很多事情,包括来自OpenCV的createBackgroundSubtractormog2或threshold。我还尝试通过从前景中减去背景像素来删除背景像素,因为我有一组237个背景图像(2个)(地毯没有浪费,但与带有对象的图像相比有一点偏移)。背景图像的亮度也有所不同。

(2) Example of a background image

这是一个我可以测试的代码示例,它为我提供了下面的(3)和(4)。我使用的是Python 3.8.3。

# Function to remove the sides of the images
def delete_side(img,x_left,x_right):
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            if j<=x_left or j>=x_right:
                img[i,j] = (0,0)
    return img

# Intialize the background model
backSub = cv2.createBackgroundSubtractormog2(history=250,varThreshold=2,detectShadows=True)

# Read the frames and update the background model
for frame in frames:
    if frame.endswith(".png"):
        filepath = FRAMES_FOLDER + '/' + frame
        img = cv2.imread(filepath)
        img_cut = delete_side(img,x_left=190,x_right=1280)
        gray = cv2.cvtColor(img_cut,cv2.COLOR_BGR2GRAY)
        mask = backSub.apply(gray)
        newimage = cv2.bitwise_or(img,img,mask=mask)
        img_blurred = cv2.GaussianBlur(newimage,(5,5),0)
        gray2 = cv2.cvtColor(img_blurred,cv2.COLOR_BGR2GRAY)
        _,binary = cv2.threshold(gray2,10,255,cv2.THRESH_BINARY)
        final = cv2.bitwise_or(img,mask=binary)
        newpath = RESULT_FOLDER + '/' + frame
        cv2.imwrite(newpath,final)

我从Stackoverflow上发现的许多其他案例或其他案例(例如:removing pixels less than n size(noise) in an image - open CV python)中得到启发。

(3) The result obtained with the code above

(4) Result when increasing the varThreshold argument to 10

不幸的是,生成图片上仍然有很多噪点。

作为“背景减法”的初学者,我没有获得最佳解决方案的所有关键。如果有人想以一种更高效,更干净的方式来完成此任务(是否有一种特殊的方法来处理透明物体的情况?可以更有效地消除物体上的噪音吗?等),我很感兴趣:) 谢谢

解决方法

感谢您的回答。对于信息,我只是简单地改变方法并使用带有2个标签(前景,背景)的细分模型(U-Net)来识别背景。效果很好。