opencv提取图像红色部分并提取角点

#include 
#include 
#include 
#include 

using namespace cv;
using namespace std;

void rgb2hsv(double r, double g, double b, double &h, double &s, double &v) {
    r /= 255.0;
    g /= 255.0;
    b /= 255.0;
    double maximum = r, minimum = r;
    if(g > maximum) maximum = g;
    if(b > maximum) maximum = b;
    if(g < minimum) minimum = g;
    if(b < minimum) minimum = b;
    v= maximum;
    s = 0;
    if(v < 0.001 || maximum - minimum < 0.001) {
        h = 0;
    } else {
        if(v != 0) s = (v - minimum) / v;
        if(v == r) h = 60*(g-b)/(v-minimum);
        if(v == g) h = 120+60*(b-r)/(v-minimum);
        if(v == b) h = 240+60*(r-g)/(v-minimum);
        if(h < 0) h+= 360;
    }
}

Mat picture_red(Mat input)
{
    Mat frame;
    Mat srcImg = input;
    frame = srcImg;
    waitKey(1);
    int width = srcImg.cols;
    int height = srcImg.rows;
    cout << width << "," << height << endl;
    int x, y;
    double B = 0.0, G = 0.0, R = 0.0, H = 0.0, S = 0.0, V = 0.0;
    Mat vec_rgb = Mat::zeros(srcImg.size(), CV_8UC1);
    for (x = 0; x < height; x++)
    {
        for (y = 0; y < width; y++)
        {
            B = srcImg.at < Vec3b>(x, y)[0];
            G = srcImg.at < Vec3b>(x, y)[1];
            R = srcImg.at < Vec3b>(x, y)[2];
            rgb2hsv(R, G, B, H, S, V);
            //红色范围,范围参考的网上。可以自己调
            if ((H >= 0 && H <= 16) && (S >= 0.75 && S <= 1) && (V >= 0.5 && V <= 1))
                vec_rgb.at < uchar>(x, y) = 255;
            //if(x==401 && y==201)  //0 100 33
                //cout << R << "," << G<< "," << B << endl;
        }
    }
    return vec_rgb;
}

vector<Point2f> getPoint(Mat in) {
    Mat matSrc = in;
    GaussianBlur(matSrc, matSrc, Size(5, 5), 0);
    threshold(matSrc, matSrc, 100, 255, THRESH_BINARY);
    vector<Point2f> corners;
    goodFeaturesToTrack(matSrc, corners, 8, 0.01, 10, Mat());
    
    return corners;
}

int main()
{
    Mat matSrc = imread("/home/lwd/Pictures/trapezoid.png");
    Mat hsv = picture_red(matSrc);
    vector<Point2f> corners = getPoint(hsv);
    for(int i = 0; i < corners.size(); ++i){
        //cout << corners[i] << endl;
        circle(matSrc, corners[i], 1, Scalar(0,255,255), -1);
    }
    imshow("raw", matSrc);
    //imshow("red", hsv);
    waitKey();
    return 0;
}

你可能感兴趣的:(小功能,opencv)