Detection of rectangular bright area in a Image using OpenCv

后端 未结 2 2015
我在风中等你
我在风中等你 2020-12-17 03:00

I have previously asked a question Marking an interest point in an image using c++. I used the same solution and got the required point using the adaptive threshold and Blo

2条回答
  •  一生所求
    2020-12-17 03:18

    Using a simple combination of blur & threshold I managed to get this result (resized for viewing purposes):

    After that, applying erosion & the squares.cpp technique (which is a sample from OpenCV) outputs:

    which is almost the result you are looking for: the bottom part of the rectangle was successfully detected. All you need to do is increase the height of the detected rectangle (red square) to fit your area of interest.

    Code:

    Mat img = imread(argv[1]);
    
        // Blur
    Mat new_img = img.clone();
    medianBlur(new_img, new_img, 5);
    
    // Perform threshold
    double thres = 210;
    double color = 255;
    threshold(new_img, new_img, thres, color, CV_THRESH_BINARY);
    imwrite("thres.png", new_img);
    
    // Execute erosion to improve the detection
    int erosion_size = 4;   
    Mat element = getStructuringElement(MORPH_CROSS,
                                       Size(2 * erosion_size + 1, 2 * erosion_size + 1),
                                       Point(erosion_size, erosion_size) );
    erode(new_img, new_img, element);
    imwrite("erode.png", new_img);
    
    vector > squares;
    find_squares(new_img, squares);
    std::cout << "squares: " << squares.size() << std::endl;
    
    draw_squares(img, squares);
    
    imwrite("area.png", img);
    

    EDIT:

    The find_squares() function returns a vector with all the squares found in the image. Because it iterates on every channel of the image, on your example it successfully detects the rectangular region in each of them, so printing squares.size() outputs 3.

    As a square can be seen as a vector of 4 (X,Y) coordinates, OpenCV express this concept as vector allowing you to access the X and Y part the coordinate.

    Now, printing squares revelead that the points were detected in a counterclockwise direction:

    1st ------ 4th
     |          |
     |          |
     |          |
    2nd ------ 3rd
    

    Following this example, its fairly obvious that if you need to increase the height of the rectangle you need to change the Y of the 1st and 4th points:

    for (int i = 0; i < squares.size(); i++)
    {
        for (int j = 0; j < squares[i].size(); j++)
        {
        //  std::cout << "# " << i << " " << squares[i][j].x << ","<< squares[i][j].y << std::endl;
            if (j == 0 || j == 3)
                squares[i][j].y = 0;
        }
    }
    

提交回复
热议问题