You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
|| 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.
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.
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:
importcv2importnumpyasnpimportmatplotlib.pyplotaspltcontour=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 whitecanvas_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 hullhull_ind=cv2.convexHull(contour, returnPoints=False) # Convex hull points indices in original contour arrayhull=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 indicesprint(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 redcanvas_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 bugdefects=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 pointsforiinrange(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) # cyancanvas_for_defects=cv2.line(canvas_for_defects, start, far, [255, 150, 255], 1) # pinkcanvas_for_defects=cv2.line(canvas_for_defects, end, far, [255, 150, 255], 1) # pinkcanvas_for_defects=cv2.circle(canvas_for_defects, start, 0, [255, 0, 0], 1) # redcanvas_for_defects=cv2.circle(canvas_for_defects, end, 0, [255, 0, 0], 1) # redcanvas_for_defects=cv2.circle(canvas_for_defects, far, 0, [0, 0, 255], 1) # blueplt.imshow(canvas_for_defects)
plt.show()
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.
@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
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 😀.
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:
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?
@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.
@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.
@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.
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.
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().
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):
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.
Activity
kfrance commentedon Jul 18, 2017
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.
hannarud commentedon Jan 3, 2019
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.convexHullreturns 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:
sturkmen72 commentedon Jan 3, 2019
@hannarud you are right. using your points i created the image and test it with the code below.
program output:
code:
saskatchewancatch commentedon Oct 1, 2019
@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/
hannarud commentedon Oct 1, 2019
@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
saskatchewancatch commentedon Jan 8, 2020
What I think:
convexHullimplementation is fine, and it's fine for returned indices to not be monotonic.Why:
(0, 0)@(index 0),(0, 1)@(index 1),(1, 0)@(index 2),(1, 1)@(index 3).convexHull. The returned indices will not necessarily be monotonic.0, 1, 3, 2back fromconvexHull, 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 inconvexityDefects.@hannarud @sturkmen72 any thoughts? BTW I may be totally off, my tech. background is not Comp. Geometry 😀.
hannarud commentedon Jan 8, 2020
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.
saskatchewancatch commentedon Jan 22, 2020
@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.
VadimLevin commentedon Feb 3, 2020
@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:
convexityDefectsthat 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.convexityDefectsfunction to work with such kind ofconvexHulloutput.You are welcome to resolve this issue if you can.
partially fixed the issue opencv#4539
vpisarev commentedon Feb 16, 2020
@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.
vpisarev commentedon Feb 16, 2020
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.
added yet another part to the test for issue opencv#4539, where we ru…
Merge pull request opencv#16594 from vpisarev:hull_ordering_fix
bug fix to Inconsistent comment for EXIF issue id opencv#15706 strea…
TheFlashBandicoot commentedon Jan 25, 2021
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)wout-vitestro commentedon Mar 13, 2026
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):
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
Merge pull request opencv#16594 from vpisarev:hull_ordering_fix