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

时间:2018-08-22 10:18:43

标签: c++ opencv

before

这是不戴口罩的人

after

这是涂口罩的那个

即使它隐约地检测到了,我也想更清楚一点。

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);
}

我如何使其更加清晰?

0 个答案:

没有答案