How to do it...

Once an algorithm has been encapsulated in a class using the strategy design pattern, it can be deployed by creating an instance of that class. Typically, the instance will be created when the program is initialized. At the time of construction, the class instance will initialize the different parameters of the algorithm with their default values, such that it will immediately be ready to be used. The algorithm's parameter values can also be read and set by using appropriate methods. In the case of an application with a GUI, these parameters can be displayed and modified using different widgets (text fields, sliders, and so on) so that a user can play with them easily.

We will show you the structure of a Strategy class in the next section; let's start with an example of how it can be deployed and used. Let's write a simple main function that will run our proposed color detection algorithm:

  1. First, in the main function, we have to create an instance of our created class that we will cover in the next section:
int main() 
{ 
   // 1. Create image processor object 
   ColorDetector cdetect;
  1. Read an image to process:
   // 2. Read input image 
   cv::Mat image= cv::imread("boldt.jpg"); 
  1. Check with the empty function whether we have loaded the image correctly; if it's empty, we must exit from our application:
   if (image.empty()) 
      return 0;  
  1. Use the new instance of ColorDetector to set the target color. This function is defined in the class that we will cover in the next section:
// 3. Set input parameters 
   cdetect.setTargetColor(230,190,130); // here blue sky 
  1. Create a window to show the result of the image process with our instance. To do it, we have to use the function process of our instance:
   cv::namedWindow("result"); 
 
   // 4. Process the image and display the result 
   cv::imshow("result",cdetect.process(image)); 
  1. Finally, wait for a key press before exiting:
cv::waitKey(); 
 
   return 0; 
} 

Running this program to detect a blue sky in the color version of the castle image presented in Chapter 2, Manipulating the Pixels, produces the following output:

Here, a white pixel indicates a positive detection of the sought color, and black indicates a negative detection.

Obviously, the algorithm we encapsulated in this class is relatively simple (as you will see next, it is composed of just one scanning loop and one tolerance parameter). The strategy design pattern becomes really powerful when the algorithm to be implemented is more complex, has many steps, and includes several parameters.