schirrel
schirrel

Reputation: 303

cvtColor too Slow

I'm making a project where i need to change the lightness, and contrast of an image, it's lightness not brightness. So my code at the start was

for (int y = 0; y < dst.rows; y++) {
    for (int x = 0; x < dst.cols; x++) {

        int b = dst.data[dst.channels() * (dst.cols * y + x) + 0];
        int g = dst.data[dst.channels() * (dst.cols * y + x) + 1];
        int r = dst.data[dst.channels() * (dst.cols * y + x) + 2];
... other processing stuff i'm doing

and it's good, doing it really fast, but when i try to make the hsv to hsl conversion to set the l value that i need it gets reaaaaaaally slow;

my hsl to hsl lines of code are

        cvtColor(dst, dst, CV_BGR2HSV);

        Vec3b pixel = dst.at<cv::Vec3b>(y, x); // read pixel (0,0) 
         double H = pixel.val[0];
         double S = pixel.val[1];
         double V = pixel.val[2];
           h = H;
           l = (2 - S) * V;
           s = s * V;
           s /= (l <= 1) ? (l) : 2 - (l);
           l /= 2;

              /* i will further make here the calcs to set the l i want */
           H = h;
           l *= 2;
           s *= (l <= 1) ? l : 2 - l;
           V = (l + s) / 2;
           S = (2 * s) / (l + s);

           pixel.val[0] = H;
           pixel.val[1] = S;
           pixel.val[2] = V;

           cvtColor(dst, dst, CV_HSV2BGR);

and i ran it and was slow, so i was take of the lines to see which one was making it slow and i figure out it was cvtColor(dst, dst, CV_BGR2HSV); So there's a way to make it faster than using cvtCOlor, or its time issue is something that can be handled?

Upvotes: 1

Views: 1867

Answers (1)

carlosdc
carlosdc

Reputation: 12152

I think (I haven't opened the text editor, but it seems) that you need to generate the entire image in HSV and then call cvtColor once for the entire image. Meaning that you should call cvtColor once instead of once for every pixel. That should give you a significant boost in speed.

You would do this:

  cvtColor(dst, dst, CV_BGR2HSV);

  for (int y = 0; y < dst.rows; y++) {
      for (int x = 0; x < dst.cols; x++) {


        Vec3b pixel = dst.at<cv::Vec3b>(y, x); // read current pixel 
         double H = pixel.val[0];
         double S = pixel.val[1];
         double V = pixel.val[2];
           h = H;
           l = (2 - S) * V;
           s = s * V;
           s /= (l <= 1) ? (l) : 2 - (l);
           l /= 2;

           H = h;
           l *= 2;
           s *= (l <= 1) ? l : 2 - l;
           V = (l + s) / 2;
           S = (2 * s) / (l + s);

           pixel.val[0] = H;
           pixel.val[1] = S;
           pixel.val[2] = V;
    }
}

cvtColor(dst, dst, CV_HSV2BGR);

Upvotes: 3

Related Questions