Note that there are some explanatory texts on larger screens.

plurals
  1. POefficiently threshold red using HSV in OpenCV
    text
    copied!<p>I'm trying to threshold red pixels in a video stream using OpenCV. I have other colors working quite nicely, but red poses a problem because it wraps around the hue axis (ie. HSV(0, 255, 255) and HSV(179, 255, 255) are both red). The technique I'm using now is less than ideal. Basically:</p> <pre><code>cvInRangeS(src, cvScalar(0, 135, 135), cvScalar(20, 255, 255), dstA); cvInRangeS(src, cvScalar(159, 135, 135), cvScalar(179, 255, 255), dstB); cvOr(dstA, dstB, dst); </code></pre> <p>This is suboptimal because it requires a branch in the code for red (potential bugs), the allocation of two extra images, and two extra operations when compared to the easy case of blue:</p> <pre><code>cvInRangeS(src, cvScalar(100, 135, 135), cvScalar(140, 255, 255), dst); </code></pre> <hr> <p>The nicer alternative that occurred to me was to "rotate" the image's colors, so that the target hue is at 90 degrees. Eg.</p> <pre><code>int rotation = 90 - 179; // 179 = red cvAddS(src, cvScalar(rotation, 0, 0), dst1); cvInRangeS(dst1, cvScalar(70, 135, 135), cvScalar(110, 255, 255), dst); </code></pre> <p>This allows me to treat all colors similarly.</p> <p>However, the <code>cvAddS</code> operation doesn't wrap the hue values back to 180 when they go below 0, so you lose data. I looked at converting the image to <code>CvMat</code> so that I could subtract from it and then use modulus to wrap the negative values back to the top of the range, but <code>CvMat</code> doesn't seem to support modulus. Of course, I could iterate over every pixel, but I'm concerned that that's going to be very slow.</p> <hr> <p>I've read many tutorials and code samples, but they all seem to conveniently only look at ranges that don't wrap around the hue spectrum, or use solutions that are even uglier (eg. re-implementing <code>cvInRangeS</code> by iterating over every pixel and doing manual comparisons against a color table).</p> <p>So, what's the usual way to solve this? What's the best way? What are the tradeoffs of each? Is iterating over pixels much slower than using built-in CV functions?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload