Controlling opencv convex hull

I want to combine objects on this image (threshold) under a convex hull:

import cv2
img = cv2.imread('test.png') #thresh1

ret, threshed_img = cv2.threshold(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY),
                        220, 255, cv2.THRESH_BINARY)

image, contours, hier = cv2.findContours(threshed_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for cnt in contours:
    # get convex hull
    hull = cv2.convexHull(cnt)
    cv2.drawContours(img, [hull], -1, (0, 0, 255), 1)    
cv2.imwrite("output.png", img)

enter image description here enter image description here

I can make a convex hull by manipulating the threshold:

rect_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 30))
threshed = cv2.morphologyEx(threshed_img, cv2.MORPH_CLOSE, rect_kernel)
cv2.imwrite('thresh2.png', threshed)

imgContours, Contours, Hierarchy = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for cnt in Contours:
    hull = cv2.convexHull(cnt)
    cv2.drawContours(img, [hull], -1, (0, 0, 255), 1) 
cv2.imwrite('output2.png', img)

enter image description here enter image description here

What I want is this:

enter image description here

  1. Is there a better way to combine objects under convex hulls than manipulating the threshold?
  2. How would I achieve shown convex hull?

Upvotes: 2

Views: 3539

Answers (1)

Piotr Kurowski
Piotr Kurowski

Reputation: 366

You can calculate convex hull for small pieces like on this image.

enter image description here

Then add some convex hull points to contour create by You. Those points should be:

a) extreme left point of every convex hull (with lowest x coordinate)

b) extreme right point of every convex hull (with highest x coordinate)

c) the highest point (with lowest y coordinate) from all of 5 convex hull's.

d) the lowest point (with highest y coordinate) from all of 5 convex hull's.

Your result contour will look similar to

enter image description here

Some of points will be outside the contour. If all the points should be inside contour You can check for all of the points from the 5 calculated before convex hull's if there are inside result contour or not (with pointPolygonTest function). It they are not just add them to result contour.

Upvotes: 4

Related Questions