【问题标题】:Thresholding for a colour in opencvopencv中颜色的阈值
【发布时间】:2012-01-30 23:49:50
【问题描述】:

我正在尝试将我的程序设置为颜色阈值(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;

}

【问题讨论】:

  • 请指定运行代码时显示什么问题?无论如何,最好尝试将图像转换为 HSV 以获得良好的效果。

标签: opencv colors threshold


【解决方案1】:

为颜色阈值,

1) 将图像转换为 HSV

2) 然后应用 cvInrangeS

3) 获得阈值图像后,您可以计算其中的白色像素数。

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

【讨论】:

  • 断开的链接:在 OpenCV 中跟踪彩色对象
【解决方案2】:

我可以告诉如何在 Python 和 C++ 中执行此操作,无论是否转换为 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)

来源:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多