OpenCV floodfill while maintaining intensity of objects takes too long to run <p>I am using OpenCV 3.1.0 to change the color of certain areas in an image. OpenCV's floodfill is doing an excellent job of selecting the area and changing the color to a solid new value. But the output image pixels lose their intensity and the shadows in the images are lost.</p> <p>What I need is that the color replacement in floodfill takes into consideration the intensity of the pixel and fill a slightly darker or lighter shade of that color accordingly.</p> <p>What I did -</p> <ol> <li>Converted the original image to HLS color space and saved this Mat separately. Original Image link- <a href="https://www.walldevil.com/wallpapers/a40/thumb/desktop-themes-skins-office-wallpapers-walls.jpg" rel="nofollow">https://www.walldevil.com/wallpapers/a40/thumb/desktop-themes-skins-office-wallpapers-walls.jpg</a></li> <li>Used floodfill on image with new color. Convert this to HLS too. </li> <li>Parsed each pixel of the new image and wherever the floodfill had replaced the color, changed the L value by incrementing or decrementing the new L with the difference between the old L and average L of changed pixels. <a href="http://i.stack.imgur.com/gMVWk.png" rel="nofollow">Output after Intensity Readjustment</a></li> </ol> <p>The problem is first I calculated the average L of changed pixels and then parse each pixel again to adjust the L value. All this is taking too long to execute</p> <p>Is there a way I can optimize my approach for faster output.</p> <pre><code>Mat dst = isColor ? image : gray; int area; if( useMask ) { threshold(mask, mask, 1, 128, THRESH_BINARY); area = floodFill(dst, mask, seed, newVal, &amp;ccomp, Scalar(lo, lo, lo), Scalar(up, up, up), flags); imshow( "mask", mask ); } else { area = floodFill(dst, seed, newVal, &amp;ccomp, Scalar(lo, lo, lo), Scalar(up, up, up), flags); } cvtColor(dst,hsvmask,CV_BGR2HLS); for(int i=0;i&lt;image.rows;i++) for(int j=1;j&lt;image.cols*3;j=j+3) { float o_hue=(float)imghsv.at&lt;uchar&gt;(i,j); float n_hue=(float)hsvmask.at&lt;uchar&gt;(i,j); float s_intensity=(float)imghsv.at&lt;uchar&gt;(y,x*3+1); float o_intensity=(float)imghsv.at&lt;uchar&gt;(i,j); float n_intensity=(float)hsvmask.at&lt;uchar&gt;(i,j); float newIntensity=n_intensity + (o_intensity-s_intensity); hsvmask.at&lt;uchar&gt;(i,j)=((o_hue==n_hue)?o_intensity:newIntensity&lt;0?0:newIntensity); } hsvmask.copyTo(imghsv); cvtColor(hsvmask,dst,CV_HLS2BGR); imshow("image", dst); </code></pre> <p>The code in nested for loops is how I restore the intensity by traversing each pixel. But it is very slow in terms of execution.</p>