iOS:OpenCV红色范围

时间:2015-07-15 07:06:34

标签: ios opencv bgr

我试图用OpenCV库在图片中包围红色。我在谷歌看过很多问题,但没有人帮我。我的代码如下:

void highLightRed(const cv::Mat& inputFrame, cv::Mat& outputFrame)
{
cv::Mat gray, edges, red, blurred;

// blur will enhance edge detection
medianBlur(inputFrame, blurred, 9);

// give image in gray color space
getGray(blurred, gray);

cv::inRange(gray, cv::Scalar(0,0,112), cv::Scalar(60,0,225), red); //BGR

// using Canny algorithm to find edges
cv::Canny(red, edges, 50, 150);

std::vector< std::vector<cv::Point> > c;

// find contours of edges
cv::findContours(edges, c, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);

NSLog(@"size: %lu", c.size());

inputFrame.copyTo(outputFrame);

// draw contour in green (0,200,0) with thinkness 3
//cv::drawContours(outputFrame, c, -1, cv::Scalar(0,200,0),3);
cv::drawContours(outputFrame, c, -1, cv::Scalar(0,200,0),2);

}

void getGray(const cv::Mat& input, cv::Mat& gray)
{
const int numChannes = input.channels();

if (numChannes == 4)
{
    cv::cvtColor(input, gray, cv::COLOR_BGRA2GRAY);
}
}

问题:如果图片中只有红色和白色,则此代码工作正常,成功环绕红色。但如果涉及多种颜色,特别是深色,则颜色检测失败。 我需要只检测红色的精确范围。感谢

1 个答案:

答案 0 :(得分:0)

以BGR或RGB格式查找确切的颜色范围非常困难。你将不得不玩很多(如果你是一个新手)。

一种非常简单的方法:

  1. 使用cvtColor()
  2. 将图片转换为HSV格式
  3. 将您的HSV image拆分为三个频道,即H,S和V频道。
  4. H-channel中提取红色。您可以查看here以查找红色的色调范围。
  5. 将此新H-channel与旧的SV频道合并。
  6. 转换回BGR格式。现在你的BGR图像只包含红色。