Skip to content

Incorrect convex hull for contour. #24907

Closed

Description

@ZhivaevDmitry

System Information

OpenCV python version: 4.8.1
Operating System / Platform: Windows 10
Python version: 3.11.5

Detailed description

The "convexHull" function produces an incorrect result for the outer contour, making any further data processing and information extraction from the contour impossible. In my opinion, this contour is correct and does not have self-intersections, but it has two points of self-contact, which causes the incorrect result.

zoom_0
zoom

Output log:

Contour:
[...

 [[ 74 100]]

 [[ 74 102]]

 [[ 73 103]]

 [[ 72 103]]

 [[ 73 103]]

 [[ 74 102]]

 [[ 83 102]]

 ...]
Convex hull:
[
 ...
 [37]
 [47]
 [46]
 [50]
 ...]

Expected:

Convex hull:
[
 ...
 [37]
 [47]
 [48]
 [50]
 ...]

Steps to reproduce

greyscale.zip

import cv2 as cv

src_greyscale = cv.imread("greyscale.png", cv.IMREAD_GRAYSCALE)

contours, hierarchy = cv.findContours(src_greyscale, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)  

convex_hull_indices = cv.convexHull(contours[0], clockwise = True, returnPoints = False)

print("Contour:")
print(contours[0])
print("Convex hull:")
print(convex_hull_indices)

Issue submission checklist

  • I report the issue, it's not a question
  • I checked the problem with documentation, FAQ, open issues, forum.opencv.org, Stack Overflow, etc and have not found any solution
  • I updated to the latest OpenCV version and the issue is still there
  • There is reproducer code and related data files (videos, images, onnx, etc)

Activity

  1. added
    needs investigation
    on Jan 22, 2024
  2. mshabunin commented on Jan 22, 2024

    @mshabunin
    Contributor

    @ZhivaevDmitry , isn't it a duplicate of #4954?

  3. ZhivaevDmitry commented on Jan 22, 2024

    @ZhivaevDmitry
    Author

    @ZhivaevDmitry , isn't it a duplicate of #4954?

    Yes, that's it, and for 8 years, no one bothered to fix it. I think it's time to remind about this issue again. I really hope we won't forget about it for another 8 years. Considering that it's an extremely trivial algorithm, which is very easy to implement. Finding the convex hull is just the basics. Sorry for the emotions.

  4. ZhivaevDmitry commented on Jan 22, 2024

    @ZhivaevDmitry
    Author

    I wrote a quick fix for my project, It recalculate Convex Hull using other library if monotonous problem detected. Maybe it will be useful to someone.

    
    import cv2 as cv
    import numpy as np
    from scipy.spatial import ConvexHull
    
    def DetIsMonotonousClockwiseConvexHull(convex_hull_indices_):
                    
        index = 0
        
        prev_val = -1
        
        all_ok = True
    
        while index < convex_hull_indices_.shape[0] and all_ok:
            
            curr_val = convex_hull_indices_[index][0]
            
            all_ok = (prev_val < curr_val)
            
            prev_val = curr_val
            
            index = index + 1
    
        return all_ok
    
    
    def FixClockwiseConvexHullIfNeeded(src_convex_hull_indices_, contour_):
    
        if DetIsMonotonousClockwiseConvexHull(src_convex_hull_indices_):
            return src_convex_hull_indices_
                
        recalculated_convex_hull = ConvexHull(np.squeeze(contour_))    
        
        return np.array(sorted([[index] for index in recalculated_convex_hull.vertices]))
    
    

    greyscale2_scaled
    greyscale2.png.zip

    src_greyscale = cv.imread("greyscale2.png", cv.IMREAD_GRAYSCALE)
    
    contours, hierarchy = cv.findContours(src_greyscale, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)  
    
    convex_hull_indices = cv.convexHull(contours[0], clockwise = True, returnPoints = False)
    
    print("Before:")
    print(convex_hull_indices)
    
    convex_hull_indices = FixClockwiseConvexHullIfNeeded(convex_hull_indices, contours[0])
    
    print("After:")
    print(convex_hull_indices)
    

    Output:

    Before:
    [[3]
     [2]
     [5]
     [0]]
    After:
    [[0]
     [3]
     [4]
     [5]]
    
  5. ZhivaevDmitry commented on Jan 23, 2024

    @ZhivaevDmitry
    Author

    https://docs.opencv.org/4.x/d3/dc0/group__imgproc__shape.html#ga014b28e56cb8854c0de4a211cb2be656 https://docs.opencv.org/4.x/d0/de3/citelist.html#CITEREF_Sklansky82 https://math.stackexchange.com/questions/2632754/why-is-sklansky-algorithm-convex-hull-wrong

    sklansky-algorithm for convex hull is wrong then opencv result for convex hull is wrong

    It's extremely interesting that the incorrectness of the algorithm has already been identified and proven. Perhaps some hybrid scheme will allow solving this problem, a mixture of several algorithms. This issue, as I understand it, arises extremely rarely, and I accidentally discovered it when adding random noise to my original dataset. Out of 100,000 original images, this error manifested itself in only one.

    As I see it, it is quite clear when the convex hull becomes incorrect - this can be easily detected if Monotonous is violated. Perhaps it is worth adding some post-processor that would trigger in case of Monotonous violation.

  6. mshabunin commented on Jan 24, 2024

    @mshabunin
    Contributor

    I've done a bit more digging and found related issues #4539 and #5908. Perhaps the root cause of all problems is that convexHull function does not accept contour, but a set of points. While convexityDefects requres contour (simple polygon) as input. Due to this convexHull can shuffle points and produce incorrect output from the contour (simple polygon) convex hull point of view.

    So I beleive instead of patching this mess further we need either separate function to calculate convex hull of contours (simple polygons) or a flag/mode/autodetection in the current convexHull function.

    Additionally, looks like contours returned by findContours are not simple polygons because they might have points of self-contact which are basically self-intersections. So additional output processing is required here as well.

    Links:

  7. YanBC commented on Aug 2, 2024

    @YanBC

    @ZhivaevDmitry I apologize if this sounds naive and perhaps I do not fully understand your problem. However since point 46 and point 48 are the same why does this final convex hull is considered wrong,

    Wrong convex hull:
    [
     ...
     [37]
     [47]
     [46]
     [50]
     ...]
    

    while the following convex hull is correct?

    Correct convex hull:
    [
     ...
     [37]
     [47]
     [48]
     [50]
     ...]
    
  8. ZhivaevDmitry commented on Aug 2, 2024

    @ZhivaevDmitry
    Author

    @YanBC Somewhere between versions 4.1 and 4.9 of OpenCV, the code responsible for cv.convexHull and cv.convexityDefects was modified. According to the new internal rules, cv.convexHull is supposed to (but doesn't always) return a monotonous array of convex hull indices, i.e., h[i] < h[i+1]. Furthermore, now if you pass a non-monotonous array of convex hull indices to cv.convexityDefects, an error will be thrown:

    .../convhull.cpp:360: error: (-5 argument) The convex hull indices are not monotonous, which can be in the case when the input contour contains self-intersections in function 'convexityDefects'

  9. opencv-alalek commented on Aug 3, 2024

    @opencv-alalek
    Contributor

    relates #16594

  10. ZhivaevDmitry commented on Aug 3, 2024

    @ZhivaevDmitry
    Author

    @opencv-alalek Yes, here is another minimalistic example demonstrating the problem:

    OpenCV python version: 4.9.0
    Operating System / Platform: Windows 10
    Python version: 3.11.5

    input: grayscale

    black_and_white = cv.imread(path_to_file, cv.IMREAD_GRAYSCALE)
    
    print (black_and_white)
        
    contours, hierarchy = cv.findContours(black_and_white, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)        
    
    convex_hull_indices = cv.convexHull(contours[0], clockwise = True, returnPoints = False)
    
    print(convex_hull_indices)
    

    results:

    [[  0   0   0   0   0   0   0   0]
     [  0   0   0   0   0   0   0   0]
     [  0   0   0 255 255 255 255   0]
     [  0   0   0 255 255 255 255   0]
     [  0   0   0 255 255 255 255   0]
     [  0 255 255   0   0   0   0   0]
     [  0   0   0   0   0   0   0   0]
     [  0   0   0   0   0   0   0   0]]
     
    
    [[3]
     [2]
     [6]
     [7]
     [0]]
    
  11. added this to the 4.11.0 milestone on Aug 3, 2024
  12. modified the milestones: 4.11.0, 4.12.0 on Dec 26, 2024
  13. modified the milestones: 4.12.0, 4.13.0 on Jun 19, 2025
  14. self-assigned this
    on Nov 19, 2025
  15. asmorkalov commented on Dec 5, 2025

    @asmorkalov
    Contributor

    @dkurt Do you have progress with the issue?

  16. dkurt commented on Dec 5, 2025

    @dkurt
    Member

    @asmorkalov not started yet

  17. asmorkalov commented on Dec 9, 2025

    @asmorkalov
    Contributor

    Still reproducible with current 4.x (pre 4.13.0).

  18. added a commit that references this issue on Dec 19, 2025
  19. 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

bugcategory: imgprocneeds investigation

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions