1

我正在尝试将我的程序设置为颜色的阈值(BGR 格式)。我还没有完全决定要寻找哪种颜色。我还希望程序记录它检测到该颜色的像素数。到目前为止,我的代码如下,但它不起作用。

#include "cv.h"
#include "highgui.h"




int main()
{
 // Initialize capturing live feed from the camera
CvCapture* capture = 0;
capture = cvCaptureFromCAM(0);

// Couldn't get a device? Throw an error and quit
if(!capture)
{
    printf("Could not initialize capturing...\n");
    return -1;
}
 // The two windows we'll be using
cvNamedWindow("video");
cvNamedWindow("thresh");

 // An infinite loop
while(true)
{
    // Will hold a frame captured from the camera
    IplImage* frame = 0;
    frame = cvQueryFrame(capture);

            // If we couldn't grab a frame... quit
    if(!frame)
        break;


    //create image where threshloded image will be stored
    IplImage* imgThreshed = cvCreateImage(cvGetSize(frame), 8, 1);


    //i want to keep it BGR format. Im not sure what colour i will be looking for yet. this can be easily changed
    cvInRangeS(frame, cvScalar(20, 100, 100), cvScalar(30, 255, 255), imgThreshed);


    //show the original feed and thresholded feed
    cvShowImage("thresh", imgThreshed);
    cvShowImage("video", frame);

    // Wait for a keypress
    int c = cvWaitKey(10);
    if(c!=-1)
    {
        // If pressed, break out of the loop
        break;
    }

    cvReleaseImage(&imgThreshed);
}
cvReleaseCapture(&capture);
return 0;

}

4

2 回答 2

3

为颜色阈值,

1)将图像转换为HSV

2) 然后应用 cvInrangeS

3)一旦你得到阈值图像,你可以计算其中白色像素的数量。

试试这个教程来跟踪黄色:Tracking coloured objects in OpenCV

于 2012-01-31T04:39:02.460 回答
2

我可以告诉如何在 Python 和 C++ 中以及在转换为 HSV 和不转换为 HSV 的情况下如何做到这一点。

C++ 版本(转换为 HSV)

  1. 将图像转换为 HSV 图像:

    // Convert the image into an HSV image IplImage* imgHSV = cvCreateImage(cvGetSize(img), 8, 3); cvCvtColor(img, imgHSV, CV_BGR2HSV);

  2. 创建一个将保存阈值图像的新图像:

    IplImage* imgThreshed = cvCreateImage(cvGetSize(img), 8, 1);

  3. 使用 cvInRangeS 进行实际阈值处理

    cvInRangeS(imgHSV, cvScalar(20, 100, 100), cvScalar(30, 255, 255), imgThreshed);

这里,imgHSV 是参考图像。并且两个 cvScalar 代表颜色为黄色的值的下限和上限。(这些界限应该适用于几乎所有条件。如果没有,请尝试使用最后两个值)。

考虑任何像素。如果该像素的所有三个值(H、S 和 V,按此顺序)都在规定的范围内,则 imgThreshed 在该相应像素处获得 255 的值。这对所有像素重复。所以你最终得到的是一个阈值图像。

  1. 用于countNonZero计算阈值图像中白色像素的数量。

Python 版本(未转换为 HSV):

  1. 以 Numpy 数组格式创建您感兴趣的范围的上下边界(注意:您需要使用import numpy as np

lower = np.array((a,b,c), dtype = "uint8") upper = np.array((x,y,z), dtype = "uint8")

上面(a,b,c)是下界,(x,y,z)是上界。

2.获取满足范围的像素的掩码:

mask = cv2.inRange(image, lower, upper)

在上面,image是您要处理的图像。

  1. 使用 计算掩码中存在的白色像素的数量countNonZero

yellowpixels = cv2.countNonZero(mask) print "Number of Yellow pixels are %d" % (yellowpixels)

资料来源:

于 2016-01-05T23:19:38.037 回答