Skip to content

Indices from convexHull not monotonic #4539

Closed

Description

@opencv-pushbot

Transferred from http://code.opencv.org/issues/2922

|| Kirt Lillywhite on 2013-03-26 20:47
|| Priority: Normal
|| Affected: 2.4.4
|| Category: imgproc, video
|| Tracker: Bug
|| Difficulty: None
|| PR: 
|| Platform: None / None

Indices from convexHull not monotonic

From a segmented image I find the contour and then try to find the convexity defects from that contour. The largest convexity defect is wrong. Looking through the opencv code I think the reason is the indices from convexHull are in decreasing order except in one spot. This causes the convexityDefects function to mess up. The attached code shows the problem. I'm using 2.4.4 compiled from source on Archlinux x86-64. During compilation I turned off CUDA and enable QT, everything else is set to the default options.

History

Kirt Lillywhite on 2013-03-26 20:56
-   File mask.png added

Activity

  1. kfrance commented on Jul 18, 2017

    @kfrance

    I submitted this bug originally 4 years ago. I recently updated opencv and code with a fix to deal with this bug no longer worked. It appears that the bug has been solved in 3.2.0.

  2. hannarud commented on Jan 3, 2019

    @hannarud

    Hi! I think the issue still exists (or please clarify if it's not) - I use OpenCV 3.4.1, Python interface.

    I guess the main matter is that cv2.convexHull returns the hull points ordered differently than in original contour. After that when distances are computed for defects, some of them pass through too many points (instead of checking in-between hull points only). Not sure in this though. Can anyone help?

    My reproducible code sample:

    import cv2
    import numpy as np
    import matplotlib.pyplot as plt
    
    contour = np.array([[[26,  9]],
           [[25, 10]],
           [[24, 10]],
           [[23, 10]],
           [[22, 10]],
           [[21, 10]],
           [[20, 11]],
           [[19, 11]],
           [[18, 11]],
           [[17, 12]],
           [[17, 13]],
           [[18, 14]],
           [[18, 15]],
           [[18, 16]],
           [[18, 17]],
           [[19, 18]],
           [[19, 19]],
           [[20, 20]],
           [[21, 21]],
           [[21, 22]],
           [[22, 23]],
           [[22, 24]],
           [[23, 25]],
           [[23, 26]],
           [[24, 27]],
           [[25, 28]],
           [[26, 29]],
           [[27, 30]],
           [[27, 31]],
           [[28, 32]],
           [[29, 32]],
           [[30, 33]],
           [[31, 34]],
           [[30, 35]],
           [[29, 35]],
           [[30, 35]],
           [[31, 34]],
           [[32, 34]],
           [[33, 34]],
           [[34, 33]],
           [[35, 32]],
           [[35, 31]],
           [[35, 30]],
           [[36, 29]],
           [[37, 28]],
           [[37, 27]],
           [[38, 26]],
           [[39, 25]],
           [[40, 24]],
           [[40, 23]],
           [[41, 22]],
           [[42, 21]],
           [[42, 20]],
           [[42, 19]],
           [[43, 18]],
           [[43, 17]],
           [[44, 16]],
           [[45, 15]],
           [[45, 14]],
           [[46, 13]],
           [[46, 12]],
           [[45, 11]],
           [[44, 11]],
           [[43, 11]],
           [[42, 10]],
           [[41, 10]],
           [[40,  9]],
           [[39,  9]],
           [[38,  9]],
           [[37,  9]],
           [[36,  9]],
           [[35,  9]],
           [[34,  9]],
           [[33,  9]],
           [[32,  9]],
           [[31,  9]],
           [[30,  9]],
           [[29,  9]],
           [[28,  9]],
           [[27,  9]]], dtype=np.int32)
    print(contour.shape)
    
    canvas = np.zeros((60, 60), dtype=np.uint8)
    
    # Plot the contour in white
    canvas_for_contours = np.copy(canvas)
    canvas_for_contours = cv2.cvtColor(canvas_for_contours, cv2.COLOR_GRAY2RGB)
    canvas_for_contours = cv2.drawContours(canvas_for_contours, [contour], -1, [255,255,255], -1)
    plt.imshow(canvas_for_contours)
    plt.show()
    
    # Now find the convex hull
    hull_ind = cv2.convexHull(contour, returnPoints=False) # Convex hull points indices in original contour array
    hull = cv2.convexHull(contour, returnPoints=True) # Convex hull as contour
    
    # The next lines are possible related to https://github.com/opencv/opencv/issues/4954
    # Note that there's no matter if convexHull computed clockwise or counterclock-wise - we still see it has non-monotonous indices
    print(cv2.convexHull(contour, returnPoints=False, clockwise=False))
    print(cv2.convexHull(contour, returnPoints=False, clockwise=True))
    
    # Plot the convex hull points on the image in semi-transparent blue, points in red
    canvas_for_convhull = np.copy(canvas_for_contours)
    canvas_for_convhull = cv2.drawContours(canvas_for_convhull, [hull], -1, [0,0,255], 1)
    canvas_for_convhull = cv2.addWeighted(canvas_for_contours, 0.5, canvas_for_convhull, 0.5, 0)
    canvas_for_convhull = cv2.drawContours(canvas_for_convhull, hull, -1, [255,0,0], 1)
    plt.imshow(canvas_for_convhull)
    plt.show()
    
    # Now compute convexity defects to see the actual bug
    defects = cv2.convexityDefects(contour, hull_ind)
    print(defects)
    
    # One of the defects found - which is wrong -  [[  34   33   66 6656]]
    
    canvas_for_defects = np.copy(canvas_for_contours)
    
    # Draw all defects, its start and end points and far points
    for i in range(defects.shape[0]):
        s, e, f, d = defects[i, 0]
        start = tuple(contour[s][0])
        end = tuple(contour[e][0])
        far = tuple(contour[f][0])
    
        canvas_for_defects = cv2.line(canvas_for_defects, start, end, [128, 255, 255, ], 1)  # cyan
        canvas_for_defects = cv2.line(canvas_for_defects, start, far, [255, 150, 255], 1)  # pink
        canvas_for_defects = cv2.line(canvas_for_defects, end, far, [255, 150, 255], 1)  # pink
        canvas_for_defects = cv2.circle(canvas_for_defects, start, 0, [255, 0, 0], 1)  # red
        canvas_for_defects = cv2.circle(canvas_for_defects, end, 0, [255, 0, 0], 1)  # red
        canvas_for_defects = cv2.circle(canvas_for_defects, far, 0, [0, 0, 255], 1)  # blue
    
    plt.imshow(canvas_for_defects)
    plt.show()
  3. sturkmen72 commented on Jan 3, 2019

    @sturkmen72
    Contributor

    @hannarud you are right. using your points i created the image and test it with the code below.

    test

    program output:

    Point indexes of convexHull
    944
    816
    640
    608
    528
    544
    368
    256
    224
    160
    144
    128
    80
    0
    1056 **
    976
    960
    
    Point indexes of convexityDefects
    1008
    16
    96
    176
    240
    288
    512
    1056 **
    576
    672
    848
    

    result

    code:

    #include <opencv2/imgproc.hpp>
    #include <opencv2/highgui.hpp>
    #include <iostream>
    
    using namespace cv;
    using namespace std;
    
    int main(int argc, char** argv)
    {
        Mat bw, img = imread("test.png");
        cvtColor(img, bw, COLOR_BGR2GRAY);
        imshow("source", img);
    
        vector<vector<Point> > contours;
    
        findContours(bw, contours, RETR_LIST, CHAIN_APPROX_NONE);
    
        drawContours(img, contours, 0, Scalar(0, 0, 255), 2);
    
        vector<int> hull;
        convexHull(contours[0], hull);
    
        vector<Point> hullpts;
        cout << "\nPoint indexes of convexHull\n";
        for (const auto &e : hull)
        {
            hullpts.push_back(contours[0][e]);
            line(img, contours[0][e], contours[0][e], Scalar(0, 255, 0), 5);
            cout << e << endl;
        }
        cv::polylines(img, hullpts, true, Scalar(0, 255, 0), 1);
    
        vector<Vec4i> defects;
        convexityDefects(contours[0], hull, defects);
        cout << "\nPoint indexes of convexityDefects\n";
        for (const auto &e : defects)
        {
            line(img, contours[0][e[2]], contours[0][e[2]], Scalar(255, 0, 0), 5);
            cout << e[2] << endl;
        }
    
        imshow("result", img);
        waitKey();
    }
    
  4. saskatchewancatch commented on Oct 1, 2019

    @saskatchewancatch
    Contributor

    @sturkmen72 @hannarud @kfrance .... the doc for convexHull says that it's an implementation of the algorithm in:

    Jack Sklansky. Finding the convex hull of a simple polygon. Pattern Recognition Letters, 1(2):79–83, 1982.

    Wasn't this algorithm proven wrong? It's been shown to fail in some cases.

    BTW, I haven't reviewed the convexHull implementation to see if it is a correct implementation of Sklansky 1982. I'm just speculating that the test cases above are the kinds of polygons that cause Sklansky 1982 to fail, and that this failure is manifesting as the indices returning in the wrong order.

    Some interesting readings here: http://cgm.cs.mcgill.ca/~athens/cs601/

  5. hannarud commented on Oct 1, 2019

    @hannarud

    @saskatchewancatch thanks for noticing it.
    Actually I never checked if algorithm on which the functions are made is correct. But it looked to me that points returned by convexHull in my case were correct, what was incorrect is order of defect points. So I think, this issue still exists no matter Sklansky, 1982 algorithm is correct or not.
    But you might file a new issue on what you just wrote

  6. saskatchewancatch commented on Jan 8, 2020

    @saskatchewancatch
    Contributor

    What I think: convexHull implementation is fine, and it's fine for returned indices to not be monotonic.

    Why:

    • For a convex hull, the indices returned do not necessarily have to be in order.
      • Consider a square with points: (0, 0)@(index 0), (0, 1)@(index 1), (1, 0)@(index 2), (1, 1)@(index 3).
      • Shuffle these points in a std::vector and pass it to convexHull. The returned indices will not necessarily be monotonic.
        • In one case, I get 0, 1, 3, 2 back from convexHull, which is not monotonic, but it's still correct.

    IMO the inquiry should be into convexityDefects, which should be able to handle the set of inputs it was given in the OP's example above. I think the problem lies entirely in convexityDefects.

    @hannarud @sturkmen72 any thoughts? BTW I may be totally off, my tech. background is not Comp. Geometry 😀.

  7. hannarud commented on Jan 8, 2020

    @hannarud

    Hi @saskatchewancatch!
    You think it right. It is ok for indices to not be monotonic.
    But - that's what I point out in my example - this is ok until the points which are marked by the indices really make some convex figure in the end. If you refer back to my code sample when we get the convex hull points they seem to be totally correct:

    ((46 13), (42 21), (35 32), (33 34), (30 35), (29 35), (23 26), (19 19), (18 17), (17 13), (17 12), (18 11), (21 10), (26 9), (40 9), (45 11), (46 12))

    And they really make convex from when plotted.
    If we obtain indices from the same function, we get:

    (59, 51, 40, 38, 33, 34, 23, 16, 14, 10, 9, 8, 5, 0, 66, 61, 60) (note: 38-33-34! non-monotonous part)

    In the original contour, two points have the same value, number 33 and number 35. And instead of 33 in the indices, we should have 35.

    37 [[32 34]]
    36 [[31 34]]
    35 [[30 35]] ** - is not present in the output, but should be!
    34 [[29 35]] - point of convex hull
    33 [[30 35]] ** - outputted as a convex hull point, but this is wrong
    32 [[31 34]]
    31 [[30 33]]
    30 [[29 32]]
    29 [[28 32]]
    28 [[27 31]]
    27 [[27 30]]
    26 [[26 29]]
    25 [[25 28]]
    24 [[24 27]]
    23 [[23 26]] - point of convex hull```
    
    Did you get what I mean here?
    
  8. added
    Hackathon
    on Jan 21, 2020
  9. saskatchewancatch commented on Jan 22, 2020

    @saskatchewancatch
    Contributor

    @hannarud hannahrud, thank you for your detailed reply.

    I get what you mean. But I seem to think that it's fine that convexHull returned the point with index 33 instead of the same point with index 35. The output of the algorithm is supposed to be a convex set.

    Whether convexHull returns the point at index 33 or 35, it would be a convex set, and the answer is just as valid.

    Any thoughts? Btw thank you for your analysis so far, I think this info will be helpful for whoever is doing the hackathon.

  10. VadimLevin commented on Feb 3, 2020

    @VadimLevin
    Contributor

    @saskatchewancatch and @hannarud thank you for the detailed investigation of the problem. I wrote a small to-do list for Hackathon based on your conversation:

    • Add a test for convexityDefects that reproduce the problem with wrong order of input points. Test data can be generated using examples kindly provided by @hannarud. General idea is to have 2 or more equal points in the original contour. The test should fail.
    • Adjust convexityDefects function to work with such kind of convexHull output.
    • Check that the problem is resolved and the failed test is passed.
    • Publish a PR.

    You are welcome to resolve this issue if you can.

  11. self-assigned this
    on Feb 15, 2020
  12. vpisarev commented on Feb 16, 2020

    @vpisarev
    Contributor

    @kfrance, @hannarud, @sturkmen72, @saskatchewancatch, @VadimLevin, the issue is mostly fixed. Without that 1 pixel-wide "hair" on the contour, which can be made more thick or completely eliminated using morphological operations, everything now works well. With this "hair" an exception is now thrown by convexityDefects. For now I do not have a good solution to produce a good convex hull for such a contour. It's not a problem of Sklansky algorithm, I believe, it's that this particular case can be considered as a contour with self-intersection. A contour with self-intersection is basically not a contour, it's rather a generic point set, and for such a set it's impossible to generate a completely ordered convex hull. But at least such case is now caught by convexityDetects instead of silently producing incorrect results.

  13. vpisarev commented on Feb 16, 2020

    @vpisarev
    Contributor

    BTW, it's said in several places that Sklansky algorithm is incorrect. This is true, but only when we are talking about O(N) Sklansky algorithm that computes convex hulls for polygons. OpenCV does not have a function to compute convex hull for polygons. It computes convex hull for unordered 2D point sets. The complexity is O(N*log(N)), not O(N). And the Sklansky algorithm in OpenCV iterates though the points in a certain sorted order, not in the original order. So, the counter-examples, developed by Toussaint et al, are not applicable to our implementation. I cannot claim, of course, that our implementation is completely bug-free. I'm just saying that OpenCV implementation does not have the same problem as the original Skansky'82 O(N) algorithm.

  14. added a commit that references this issue on Feb 21, 2020
  15. added 2 commits that reference this issue on Feb 22, 2020
  16. TheFlashBandicoot commented on Jan 25, 2021

    @TheFlashBandicoot

    Using Python 3 and opencv 4.5.1, I encountered this same issue where the indices from convexHull() were 'not monotonic'.
    I found that for some reason the indices were returned from this function out of order.

    To resolve the issue, I simply sorted the numpy array in descending order before passing the indices to convexityDefects().

    hull = cv2.convexHull(contours, returnPoints=False)
    hull[::-1].sort(axis=0)
    defects = cv2.convexityDefects(contours, hull)

  17. wout-vitestro commented on Mar 13, 2026

    @wout-vitestro

    Please note that just sorting as mentioned in the answer above may appear to work, but will actually result in losing the convexity of the convex hull result (order matters). See below (from left to right, input image, convex hull without sorting, convex hull with sorting):

    Image Image Image

    Note that the convex hull looks a bit weird due to resizing from a super small input image. But you can clearly see that sorting causes self intersection and the convex hull is no longer convex.

    What you can do to solve it is use the solution from #28163 (or update to a version of opencv which has this solution), that is, replace the indices which make it non monotonous with indices pointing to the same coordinate which are monotonous.

    Python code to reproduce the images from above

    import cv2 as cv
    import numpy as np
    
    src_pts =  np.array([(3, 1), (2, 3), (3, 2), (2, 3), (1, 3)], dtype=np.uint8)
    src = np.zeros((5, 5), dtype=np.uint8)
    for point in src_pts:
        x, y = point
        src[y, x] = 255
    
    src_large = cv.resize(src, (500, 500), interpolation=cv.INTER_NEAREST)
    cv.imshow('Source', src_large)
    
    contours, _ = cv.findContours(src, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
    hull_indices = cv.convexHull(contours[0], returnPoints=False)
    #hull_indices[::-1].sort(axis=0)
    hull = np.array([contours[0][i].tolist()[0] for i in hull_indices])
    
    print(f"{contours[0]=}")
    print(f"{hull_indices=}")
    print(f"{hull=}")
    
    contours_resized = [c * 100 for c in contours]
    hull_resized = hull * 100
    
    drawing = np.zeros((500, 500, 3), dtype=np.uint8)
    cv.drawContours(drawing, contours_resized, 0, (255, 0, 0), 2)
    cv.imshow('Contours', drawing)
    
    drawing = np.zeros((500, 500, 3), dtype=np.uint8)
    cv.drawContours(drawing, [hull_resized], -1, (0, 255, 0), 1)
    cv.imshow('Hull', drawing)
    
    cv.waitKey()
  18. added a commit that references this issue on Jul 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Hackathonaffected: 3.4auto-transferredbugcategory: imgprocconfirmedpriority: normal

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions