OpenCV C++ forEach pixel access
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
// Define a pixel
typedef Point3_<uint8_t> Pixel;
void tic(double &t)
{
t = (double)getTickCount();
}
double toc(double &t)
{
return ((double)getTickCount() - t) / getTickFrequency();
}
void complicatedThreshold(Pixel &pixel)
{
if (pow(double(pixel.x) / 10, 2.5) > 100)
{
pixel.x = 255;
pixel.y = 255;
pixel.z = 255;
}
else
{
pixel.x = 0;
pixel.y = 0;
pixel.z = 0;
}
}
int main(int argc, char** argv)
{
Mat image = imread("butterfly.jpg");
resize(image, image, Size(), 30, 30);
cout << "Image size " << image.size() << endl;
int numTrials = 10;
double t;
cout << "Number of trials : " << numTrials << endl;
// Make two copies
Mat image1 = image.clone();
// Start timer
tic(t);
for (int n = 0; n < numTrials; n++)
{
// Naive pixel access
for (int r = 0; r < image.rows; r++)
{
for (int c = 0; c < image.cols; c++)
{
// Obtain pixel at (r, c)
Pixel pixel = image.at<Pixel>(r, c);
// Apply complicatedTreshold
complicatedThreshold(pixel);
// Put result back
image.at<Pixel>(r, c) = pixel;
}
}
}
cout << "Naive way: " << toc(t) << endl;
tic(t);
for (int n = 0; n < numTrials; n++)
{
// Parallel execution using C++11 lambda.
image1.forEach<Pixel>
(
[](Pixel &pixel, const int* position) -> void
{
complicatedThreshold(pixel);
}
);
}
cout << "forEach C++11 : " << toc(t) << endl;
return EXIT_SUCCESS;
}