I am using openmp to convert an image from RGB to gray scale.But openmp is not faster than normal, I wonder why? why single thread is faster than multi-threads? How to accelerate the speed?
here is the code:
#include <iostream>
#include <omp.h>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main() {
Mat image = imread("../family.jpg");
Mat gray(image.rows, image.cols, CV_8UC1);
time_t start, stop;
start = clock();
for (int i = 0; i < image.rows; i++)
for (int j = 0; j < image.cols; j++) {
gray.at<uchar>(i,j) = image.at<cv::Vec3b>(i,j)[0]*0.114
+ image.at<cv::Vec3b>(i,j)[1]*0.587
+ image.at<cv::Vec3b>(i,j)[2]*0.299;
}
stop = clock() - start;
cout << "time: " << stop * 1.0 / CLOCKS_PER_SEC << endl;
start = clock();
omp_set_num_threads(4);
#pragma omp parallel
{
#pragma omp for
for (int i = 0; i < image.rows; i++)
for (int j = 0; j < image.cols; j++) {
gray.at<uchar>(i,j) = image.at<cv::Vec3b>(i,j)[0]*0.114
+ image.at<cv::Vec3b>(i,j)[1]*0.587
+ image.at<cv::Vec3b>(i,j)[2]*0.299;
}
}
stop = clock() - start;
cout << "time: " << stop * 1.0 / CLOCKS_PER_SEC << endl;
return 0;
}
result:
normal time: 0.035253
openmp time: 0.069894