C++ OpenCV无法很好地检测特定颜色

C++ OpenCV无法很好地检测特定颜色,c++,opencv,C++,Opencv,这是一个没有应用遮罩的 这是一个应用的面具 尽管它检测到的信息很模糊,但我想说得更清楚 void MainWindow::updatePicture(){ Mat frame; Mat blurred; Mat grayBlurred; Mat hsvBlurred; Mat diff; Mat movingObjectMask; Mat colorMask; Mat result; this->cap.read(f

这是一个没有应用遮罩的

这是一个应用的面具

尽管它检测到的信息很模糊,但我想说得更清楚

void MainWindow::updatePicture(){
    Mat frame;
    Mat blurred;
    Mat grayBlurred;
    Mat hsvBlurred;
    Mat diff;
    Mat movingObjectMask;
    Mat colorMask;
    Mat result;
    this->cap.read(frame);
    blur(frame, blurred, Size(this->kernel, this->kernel)); // blur the frame
    cvtColor(blurred, grayBlurred, COLOR_BGR2GRAY); // convert to gray
    /* make a mask that finds a moving object */
    absdiff(this->previous, grayBlurred, diff); // compare it with previous frame which was blurred and converted to gray
    threshold(diff, movingObjectMask, this->thresholdVal, 255, THRESH_BINARY); // binarize it
    cvtColor(movingObjectMask, movingObjectMask, COLOR_GRAY2BGR);
    /* make a mask that finds a specific color */
    cvtColor(blurred, hsvBlurred, COLOR_BGR2HSV); // convert to HSV to track a color
    inRange(hsvBlurred, this->hsvLowerBound, this->hsvUpperBound, colorMask); // track the color
    cvtColor(colorMask, colorMask, COLOR_GRAY2BGR);
    /* apply the masks */
    bitwise_and(frame, movingObjectMask, result);
    bitwise_and(result, colorMask, result);
    cvtColor(result, result, COLOR_BGR2RGB);
    /* end */
    this->myLabel->setPixmap(mat2QPixmap(result, QImage::Format_RGB888));
    this->previous = grayBlurred;
}
正如您在代码中所看到的,我制作了两个遮罩,用于检测移动的对象和特定的颜色(从技术上讲,是特定范围内的颜色)

hsv上限和下限的计算如下

void MainWindow::refreshRgb(){
    Scalar lowerBound = hsvMult(this->currentHsv, 1 - this->ratio);
    Scalar upperBound = hsvMult(this->currentHsv, 1 + this->ratio);
    this->hsvLowerBound = lowerBound;
    this->hsvUpperBound = upperBound;
}

Scalar hsvMult(const Scalar& scalar, double ratio){
    int s = static_cast<int>(scalar[1]*ratio);
    int v = static_cast<int>(scalar[2]*ratio);
    if(s > 255)
        s = 255;
    if(v > 255)
        v = 255;
    return Scalar(static_cast<int>(scalar[0]), s, v);
}
void主窗口::refreshRgb(){
标量下限=hsvMult(此->当前HSV,1-此->比率);
标量上限=hsvMult(此->当前HSV,1+此->比率);
此->hsvLowerBound=下Bound;
此->hsvUpperBound=上限;
}
标量hsvMult(常量标量和标量,双倍比率){
int s=静态_cast(标量[1]*比率);
int v=静态_cast(标量[2]*比率);
如果(s>255)
s=255;
如果(v>255)
v=255;
返回标量(静态_转换(标量[0]),s,v;
}

如何使其更清晰?

对H使用更大的范围value@Miki谢谢,好多了。实验室色彩空间怎么样?