Modern CPP and OpenCV 2.4

Lately I’ve been going through the Open CV tutorials. I chose to go with the 2.4 version rather than 3.0, because, as of writing, the OpenCV entry in Arch Linux Repo doesn’t use 3.0, and I didn’t want to break any dependencies.

The 2.4 tutorials have some code that doesn’t take advantage of cpp11 and cpp14 features. So, I’ve made an effort to change the examples to use some of those features.


auto was really helpful when trying to figure out what types to use for different transforms and loops. Reducing the number of times a type has to be adjusted is really helpful.

auto table = vector<uchar>(vector<uchar>(256));
// is easier to adjust than
vector<uchar> table = vector<uchar>(vector<uchar>(256));

Clion is really helpful by providing auto complete even when automatic type deduction.

##Algorithms and Lambdas

Algorithms are helpful by providing a safer way to operate on the matrices. Rather than using raw loops to generate or transform matrices to apply custom transforms. Lambdas are great in combination with algorithms because it allows the changes to be applied inline.

Algorithms require interables to work. OpenCV Mats provide this via their begin and end methods.

The below example is from the color space reduction tutorial.

// create a table to hold color space mappings
auto table = vector<uchar>(vector<uchar>(256));
uchar index = 0;
generate(table.begin(), table.end(), [&divideWith, &index](){
		return divideWith * ((++index) / divideWith);

// transform image by moving pixel values to map (I is a cv::Mat representing image)
transform(I.begin<Vec3b>(), I.end<Vec3b>(), result->begin<Vec3b>(), [&table](Vec3b p) {
		return Vec3b([0]),[1]),[2]));

I’m still trying to get better at generating and transforming tables when in situations where the index is required. The above generate isn’t ideal, because it is obviously not thread safe.