1

I've got two contours cnt1 and cnt2. I want to check if the two contours are touching each other or not. For an example, consider the following two contours which are touching each other:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 0, 0, 1, 0],
[0, 1, 0, 0, 1, 1, 0, 0, 1, 0],
[0, 1, 0, 0, 1, 1, 0, 0, 1, 0],
[0, 1, 0, 0, 1, 1, 0, 0, 1, 0],
[0, 0, 1, 1, 1, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

To get a working example using opencv lets have two contours as follows:

labels = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                    [0, 0, 0, 0, 0, 5, 5, 5, 0, 0],
                    [0, 0, 1, 1, 1, 5, 5, 5, 0, 0],
                    [0, 0, 1, 1, 1, 5, 5, 5, 0, 0],
                    [0, 0, 1, 1, 1, 5, 5, 5, 0, 0],
                    [0, 0, 0, 0, 0, 5, 5, 5, 0, 0],
                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=np.uint8)

cnt1, hierarchy = cv2.findContours((labels==1).astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cnt2, hierarchy = cv2.findContours((labels==5).astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
Vedanshu
  • 2,230
  • 23
  • 33
  • @JeruLuke Just to detect the contours touching you would need to apply dilatation before finding the contours. – Croolman Mar 03 '20 at 07:50
  • 1
    https://stackoverflow.com/questions/55641425/check-if-two-contours-intersect This link checks for intersecting contours, this does not consider the case of touching contours. – Vedanshu Mar 03 '20 at 08:09
  • Just dilate one of them, and then bitwise and the two masks (or drawn contours) and check the total number of pixels: cv2.countNonZero(np.bitwise_and(mask_dilated, other_mask)) > 0 – Joel Teply Nov 15 '21 at 15:13

0 Answers0