OpenCV Tutorials 14 - 基于 GrabCut 算法的交互式前景提取

2,979 阅读10分钟

本小节我们主要使用GrabCut提取图像前景,另外我们还会使用GrabCut编写交互式应用进行前景提取

GrabCut 算法的交互式前景提取

一、概念

GrabCut 算法由 Carsten Rother、Vladimir Kolmogorov 设计,“GrabCut”:使用迭代图形切割的交互式前景提取。 需要一种以最少的用户交互进行前景提取的算法,结果就是 GrabCut。dl.acm.org/citation.cf…

从用户的角度来看它是如何工作的? 最初,用户在前景区域周围绘制了一个矩形(前景区域应该完全在矩形内)。 然后算法对其进行迭代分割以获得最佳结果。 完毕。 但在某些情况下,分割不会很好,例如,它可能已将某些前景区域标记为背景,反之亦然。 在这种情况下,用户需要进行精细的修饰。 只需在存在一些错误结果的图像上画一些笔画即可。 Strokes 基本上说 “嘿,这个区域应该是前景,你将其标记为背景,在下一次迭代中更正它” 或背景相反。 然后在下一次迭代中,你会得到更好的结果。

见下图。 第一名球员和足球被包围在一个蓝色矩形中。 然后用白色笔触(表示前景)和黑色笔触(表示背景)进行一些最终修饰。 我们得到了一个不错的结果。

download.jpg

  • 那么我们会对背景进行什么操作呢?
  1. 用户输入矩形。此矩形之外的所有内容都将被视为确定背景(这就是之前提到的矩形应包含所有对象的原因)。矩形内的一切都是未知的。同样,任何指定前景和背景的用户输入都被视为硬标签,这意味着它们在此过程中不会改变。
  2. 计算机根据我们提供的数据进行初始标记。它标记前景和背景像素(或硬标记)
  3. 接下来使用高斯混合模型(GMM)对前景和背景进行建模。
  4. 根据我们提供的数据,GMM 学习并创建新的像素分布。也就是说,未知像素被标记为可能的前景或可能的背景,这取决于它与其他硬标记像素在颜色统计方面的关系(就像聚类一样)。
  5. 因此像素分布构建了一个图形。图中的节点是像素。添加了额外的两个节点,Source 节点和 Sink 节点。每个前景像素都连接到 Source 节点,每个背景像素都连接到 Sink 节点。将像素连接到源节点/结束节点的边的权重由像素作为前景/背景的概率定义。
  6. 像素之间的权重由边缘信息或像素相似度定义。如果像素颜色差异很大,则它们之间的边缘将获得较低的权重。
  7. 然后使用 mincut 算法对图进行分割。它将图以最小成本函数分割成两个分离的源节点和汇节点。成本函数是被切割边的所有权重的总和。切割后,所有连接到 Source 节点的像素都变成前景,连接到 Sink 节点的像素变成背景。
  8. 该过程一直持续到分类收敛。

download.jpg

二、实例

现在我们使用 OpenCV 进行抓取算法。 OpenCV 有这个功能, cv.grabCut() 。 我们将首先看到它的参数:

  1. img - 输入图像
  2. mask - 这是一个掩码图像,我们指定哪些区域是背景、前景或可能的背景/前景等。它由以下标志完成,cv.GC_BGD、cv.GC_FGD、cv.GC_PR_BGD、cv.GC_PR_FGD , 或简单地将 0,1,2,3 传递给图像
  3. rect - 它是一个矩形的坐标,其中包括格式为 (x,y,w,h) 的前景对象
  4. bdgModel, fgdModel - 这些是算法内部使用的数组。 您只需创建两个大小为 (1,65) 的 np.float64 类型零数组。
  5. iterCount - 算法应该运行的迭代次数。
  6. mode - 它应该是 cv.GC_INIT_WITH_RECT 或 cv.GC_INIT_WITH_MASK 或组合来决定我们是绘制矩形还是最终的掩码笔触。

首先让我们看看矩形模式。 我们加载图像,创建一个类似的掩码图像。 我们创建 fgdModel 和 bgdModel。 我们给出矩形参数。 这一切都很简单。 让算法运行 5 次迭代。 模式应该是 cv.GC_INIT_WITH_RECT 因为我们使用的是矩形。 然后运行grabcut。 它修改蒙版图像。 在新的蒙版图像中,像素将被标记为上面指定的四个标志,表示背景/前景。 所以我们修改掩码,使所有 0 像素和 2 像素都设置为 0(即背景),所有 1 像素和 3 像素都设置为 1(即前景像素)。 现在我们的最终掩码已经准备好了。 只需将其与输入图像相乘即可得到分割图像。

import cv2 as cv
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
def cv_show(name, img):
    cv.imshow(name, img)
    cv.waitKey(0)
    cv.destroyAllWindows()
def compare(imgs):
  #  for i in range(len(imgs)):
 #       imgs[i][:,-3:-1,:] = [255,255,255]
    res = np.hstack(imgs)
    cv_show('Compare', res)
img = cv.imread('messi.png')
# 自定义掩膜
mask = np.zeros(img.shape[:2],np.uint8)
# 定义两个长度为65的阵列,便于算法处理
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)
# 绘出前景框
rect = (50,50,450,290)
cv.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv.GC_INIT_WITH_RECT)
mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
img = img*mask2[:,:,np.newaxis]
plt.imshow(img),plt.colorbar(),plt.show()

download.png

(<matplotlib.image.AxesImage at 0x293a78fbd90>,
 <matplotlib.colorbar.Colorbar at 0x293a7918fa0>,
 None)

哎呀,梅西的头发没了。 谁喜欢没有头发的梅西? 我们需要把它带回来。 所以我们会用 1 像素(当然是前景)进行精细修饰。 同时,地面的一些部分出现了我们不想要的图像,还有一些标志。 我们需要删除它们。 在那里,我们给出了一些 0 像素的修饰(确定背景)。 因此,正如我们现在所说的那样,我们在以前的情况下修改了我们得到的掩码。

我实际上所做的是,我在绘画应用程序中打开了输入图像,并在图像中添加了另一层。 在油漆中使用画笔工具,我用白色和不需要的背景(如标志、地面等)在这个新图层上用黑色标记了错过的前景(头发、鞋子、球等)。 然后用灰色填充剩余的背景。 然后在OpenCV中加载该掩码图像,编辑我们得到的原始掩码图像,并在新添加的掩码图像中使用相应的值。 检查下面的代码:

# newmask is the mask image I manually labelled
newmask = cv.imread('newmask.png',0)
# wherever it is marked white (sure foreground), change mask=1
# wherever it is marked black (sure background), change mask=0
mask[newmask == 0] = 0
mask[newmask == 255] = 1
mask, bgdModel, fgdModel = cv.grabCut(img,mask,None,bgdModel,fgdModel,5,cv.GC_INIT_WITH_MASK)
mask = np.where((mask==2)|(mask==0),0,1).astype('uint8')
img = img*mask[:,:,np.newaxis]
plt.imshow(img),plt.colorbar(),plt.show()

download.jpg

就是这样了。 在这里,您可以直接进入掩码模式,而不是在矩形模式下初始化。 只需用 2 像素或 3 像素(可能的背景/前景)标记蒙版图像中的矩形区域。 然后像我们在第二个示例中所做的那样,用 1 像素标记我们的sure_foreground。 然后直接应用带有遮罩模式的grabCut函数。

三、练习

1. grabcut.py in samples

#!/usr/bin/env python
'''
===============================================================================
Interactive Image Segmentation using GrabCut algorithm.

This sample shows interactive image segmentation using grabcut algorithm.

USAGE:
    python grabcut.py <filename>

README FIRST:
    Two windows will show up, one for input and one for output.

    At first, in input window, draw a rectangle around the object using the
right mouse button. Then press 'n' to segment the object (once or a few times)
For any finer touch-ups, you can press any of the keys below and draw lines on
the areas you want. Then again press 'n' to update the output.

Key '0' - To select areas of sure background
Key '1' - To select areas of sure foreground
Key '2' - To select areas of probable background
Key '3' - To select areas of probable foreground

Key 'n' - To update the segmentation
Key 'r' - To reset the setup
Key 's' - To save the results
===============================================================================
'''

# Python 2/3 compatibility
from __future__ import print_function

import numpy as np
import cv2 as cv

import sys
# 定义空函数,便于在滑轨栏变动时不触发事件
def nothing(x):
    pass


class App():
    BLUE = [255,0,0]        # rectangle color
    RED = [0,0,255]         # PR BG
    GREEN = [0,255,0]       # PR FG
    BLACK = [0,0,0]         # sure BG
    WHITE = [255,255,255]   # sure FG

    DRAW_BG = {'color' : BLACK, 'val' : 0}
    DRAW_FG = {'color' : WHITE, 'val' : 1}
    DRAW_PR_BG = {'color' : RED, 'val' : 2}
    DRAW_PR_FG = {'color' : GREEN, 'val' : 3}

    # setting up flags
    rect = (0,0,1,1)
    drawing = False         # flag for drawing curves
    rectangle = False       # flag for drawing rect
    rect_over = False       # flag to check if rect drawn
    rect_or_mask = 100      # flag for selecting rect or mask mode
    value = DRAW_FG         # drawing initialized to FG
    
    # 修改此处的画笔宽度
    thickness =  3          # brush thickness

    def onmouse(self, event, x, y, flags, param):
        # Draw Rectangle
        if event == cv.EVENT_RBUTTONDOWN:
            self.rectangle = True
            self.ix, self.iy = x,y

        elif event == cv.EVENT_MOUSEMOVE:
            if self.rectangle == True:
                self.img = self.img2.copy()
                cv.rectangle(self.img, (self.ix, self.iy), (x, y), self.BLUE, 2)
                self.rect = (min(self.ix, x), min(self.iy, y), abs(self.ix - x), abs(self.iy - y))
                self.rect_or_mask = 0

        elif event == cv.EVENT_RBUTTONUP:
            self.rectangle = False
            self.rect_over = True
            cv.rectangle(self.img, (self.ix, self.iy), (x, y), self.BLUE, 2)
            self.rect = (min(self.ix, x), min(self.iy, y), abs(self.ix - x), abs(self.iy - y))
            self.rect_or_mask = 0
            print(" Now press the key 'n' a few times until no further change \n")

        # draw touchup curves

        if event == cv.EVENT_LBUTTONDOWN:
            if self.rect_over == False:
                print("first draw rectangle \n")
            else:
                self.drawing = True
                cv.circle(self.img, (x,y), self.thickness, self.value['color'], -1)
                cv.circle(self.mask, (x,y), self.thickness, self.value['val'], -1)

        elif event == cv.EVENT_MOUSEMOVE:
            if self.drawing == True:
                cv.circle(self.img, (x, y), self.thickness, self.value['color'], -1)
                cv.circle(self.mask, (x, y), self.thickness, self.value['val'], -1)

        elif event == cv.EVENT_LBUTTONUP:
            if self.drawing == True:
                self.drawing = False
                cv.circle(self.img, (x, y), self.thickness, self.value['color'], -1)
                cv.circle(self.mask, (x, y), self.thickness, self.value['val'], -1)

    def run(self):
        # Loading images
        if len(sys.argv) == 2:
            filename = sys.argv[1] # for drawing purposes
        else:
            print("No input image given, so loading default image, lena.jpg \n")
            print("Correct Usage: python grabcut.py <filename> \n")
            filename = 'xy.png'

        self.img = cv.imread(cv.samples.findFile(filename))
        self.img2 = self.img.copy()                               # a copy of original image
        self.mask = np.zeros(self.img.shape[:2], dtype = np.uint8) # mask initialized to PR_BG
        self.output = np.zeros(self.img.shape, np.uint8)           # output image to be shown

        # input and output windows
        cv.namedWindow('output')
        cv.namedWindow('input')
        cv.setMouseCallback('input', self.onmouse)
        cv.moveWindow('input', self.img.shape[1]+10,90)
        
        # 在输入框中新建滑轨栏
        cv.createTrackbar('Thickness','input',self.thickness,30,nothing)

        print(" Instructions: \n")
        print(" Draw a rectangle around the object using right mouse button \n")

        while(1):
            
            # 添加画笔宽度的监听事件
            self.thickness = cv.getTrackbarPos('Thickness','input')
            
            cv.imshow('output', self.output)
            cv.imshow('input', self.img)
            k = cv.waitKey(1)

            # key bindings
            if k == 27:         # esc to exit
                break
            elif k == ord('0'): # BG drawing
                print(" mark background regions with left mouse button \n")
                self.value = self.DRAW_BG
            elif k == ord('1'): # FG drawing
                print(" mark foreground regions with left mouse button \n")
                self.value = self.DRAW_FG
            elif k == ord('2'): # PR_BG drawing
                self.value = self.DRAW_PR_BG
            elif k == ord('3'): # PR_FG drawing
                self.value = self.DRAW_PR_FG
            elif k == ord('s'): # save image
                bar = np.zeros((self.img.shape[0], 5, 3), np.uint8)
                res = np.hstack((self.img2, bar, self.img, bar, self.output))
                cv.imwrite('grabcut_output.png', res)
                print(" Result saved as image \n")
            elif k == ord('r'): # reset everything
                print("resetting \n")
                self.rect = (0,0,1,1)
                self.drawing = False
                self.rectangle = False
                self.rect_or_mask = 100
                self.rect_over = False
                self.value = self.DRAW_FG
                self.img = self.img2.copy()
                self.mask = np.zeros(self.img.shape[:2], dtype = np.uint8) # mask initialized to PR_BG
                self.output = np.zeros(self.img.shape, np.uint8)           # output image to be shown
            elif k == ord('n'): # segment the image
                print(""" For finer touchups, mark foreground and background after pressing keys 0-3
                and again press 'n' \n""")
                try:
                    bgdmodel = np.zeros((1, 65), np.float64)
                    fgdmodel = np.zeros((1, 65), np.float64)
                    if (self.rect_or_mask == 0):         # grabcut with rect
                        cv.grabCut(self.img2, self.mask, self.rect, bgdmodel, fgdmodel, 1, cv.GC_INIT_WITH_RECT)
                        self.rect_or_mask = 1
                    elif (self.rect_or_mask == 1):       # grabcut with mask
                        cv.grabCut(self.img2, self.mask, self.rect, bgdmodel, fgdmodel, 1, cv.GC_INIT_WITH_MASK)
                except:
                    import traceback
                    traceback.print_exc()

            mask2 = np.where((self.mask==1) + (self.mask==3), 255, 0).astype('uint8')
            self.output = cv.bitwise_and(self.img2, self.img2, mask=mask2)

        print('Done')


if __name__ == '__main__':
    print(__doc__)
    App().run()
    cv.destroyAllWindows()
===============================================================================
Interactive Image Segmentation using GrabCut algorithm.

This sample shows interactive image segmentation using grabcut algorithm.

USAGE:
    python grabcut.py <filename>

README FIRST:
    Two windows will show up, one for input and one for output.

    At first, in input window, draw a rectangle around the object using the
right mouse button. Then press 'n' to segment the object (once or a few times)
For any finer touch-ups, you can press any of the keys below and draw lines on
the areas you want. Then again press 'n' to update the output.

Key '0' - To select areas of sure background
Key '1' - To select areas of sure foreground
Key '2' - To select areas of probable background
Key '3' - To select areas of probable foreground

Key 'n' - To update the segmentation
Key 'r' - To reset the setup
Key 's' - To save the results
===============================================================================

No input image given, so loading default image, lena.jpg 

Correct Usage: python grabcut.py <filename> 

 Instructions: 

 Draw a rectangle around the object using right mouse button 

 Now press the key 'n' a few times until no further change 

 For finer touchups, mark foreground and background after pressing keys 0-3
                and again press 'n' 

 mark background regions with left mouse button 

 For finer touchups, mark foreground and background after pressing keys 0-3
                and again press 'n' 

 mark foreground regions with left mouse button 

 For finer touchups, mark foreground and background after pressing keys 0-3
                and again press 'n' 

 mark background regions with left mouse button 

 mark foreground regions with left mouse button 

 For finer touchups, mark foreground and background after pressing keys 0-3
                and again press 'n' 

 For finer touchups, mark foreground and background after pressing keys 0-3
                and again press 'n' 

 mark background regions with left mouse button 

 For finer touchups, mark foreground and background after pressing keys 0-3
                and again press 'n' 

 For finer touchups, mark foreground and background after pressing keys 0-3
                and again press 'n' 

 For finer touchups, mark foreground and background after pressing keys 0-3
                and again press 'n' 

 For finer touchups, mark foreground and background after pressing keys 0-3
                and again press 'n' 

 Result saved as image 

 Result saved as image 

 Result saved as image 

 Result saved as image 

Done

2. 小小的改进

可以在窗口加上滑轨栏来调整画笔大小。

download.png