0

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
Simon
  • 161
  • 1
  • 14
  • 1
    Why don't you compile OpenCV with OpenMP and let `cv::cvtColor(image, gray, cv::BGR2GRAY)` deal with it? – Miki Nov 24 '17 at 10:04
  • 4
    Don't use `clock`. https://stackoverflow.com/questions/10673732/openmp-time-and-clock-calculates-two-different-results – Zulan Nov 24 '17 at 10:06
  • 1
    clock is cpu time. you should measure wall time instead. – Micka Nov 24 '17 at 10:24
  • 1. well, I'm trying to learn openMP, so this function is just a test. 2. thx for new time measurement, I will try it. – Simon Nov 28 '17 at 01:49

0 Answers0