Python OpenCV GrabCut Foreground Detection

In this Python OpenCV article we are going to talk about GrabCut Foreground Detection. GrabCut algorithm was designed by Carsten Rother, Vladimir Kolmogorov & Andrew Blake from Microsoft Research Cambridge, UK.

 

 

 

Also you can check More Python GUI Development Tutorials in the below link.

1: PyQt5 GUI Development Tutorials

2: TKinter GUI Development Tutorials

3: Pyside2 GUI Development Tutorials 

4: Kivy GUI Development Tutorials

 

 

 

 

So now this is the complete code for Python OpenCV GrabCut Foreground Detection

 

 

 

now in the above code we have created zero-filled and foreground and background models.

Background and foreground models are going to be determined based on the areas left out of the initial rectangle

 

 

 

This is the rectangle code

 

 

 

So now to the interesting part! we run the GrabCut algorithm specifying the empty models
and mask, and the fact that we’re going to use a rectangle to initialize the operation:

 

 

 

You’ll also notice an integer after fgdModel, which is the number of iterations the
algorithm is going to run on the image. You can increase these, but there is a point in
which pixel classifications will converge, and effectively, you’ll just be adding iterations
without obtaining any more improvements.
After this, our mask will have changed to contain values between 0 and 3. The values, 0
and 2, will be converted into zeros, and 1-3 into ones, and stored into mask2, which we can
then use to filter out all zero-value pixels (theoretically leaving all foreground pixels
intact):

 

 

 

 

The last part of the code displays the images side by side

 

 

 

 

 

So now run the complete code and this will be the result

Python OpenCV GrabCut Foreground Detection
Python OpenCV GrabCut Foreground Detection

 

 

 

 

 

 

Also you can watch the complete video for this article 

Subscribe and Get Free Video Courses & Articles in your Email

 

Codeloop
Share via
Copy link
Powered by Social Snap
×