Segmenting an image with the GrabCut algorithm

The previous recipe showed how color information can be useful to segment an image into area corresponding to specific elements of a scene. Objects often have distinctive colors, and these ones can often be extracted by identifying areas of similar colors. OpenCV proposes an implementation of a popular algorithm for image segmentation: the GrabCut algorithm. GrabCut is a complex and computationally expensive algorithm, but it generally produces very accurate results. It is the best algorithm to use when you want to extract a foreground object in a still image (for example, to cut and paste an object from one picture to another).

How to do it…

The cv::grabCut function is easy to use. You just need to ...

Get OpenCV 3 Computer Vision Application Programming Cookbook - Third Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.