OpenCV detect contours intersection

19,620

A simple but perhaps not the most efficient (??) way would be to use drawContours to create two images: one with the contour of the car and one with the contour of the obstacle.

Then and them together, and any point that is still positive will be points of intersection.

Some pseudocode (I use the Python interface so wouldn't get the C++ syntax right, but it should be simple enough for you to convert):

import numpy as np # just for matrix manipulation, C/C++ use cv::Mat
# find contours.
contours,h = findContours( img, mode=RETR_LIST, method=CHAIN_APPROX_SIMPLE )
# Suppose this has the contours of just the car and the obstacle.

# create an image filled with zeros, single-channel, same size as img.
blank = np.zeros( img.shape[0:2] )

# copy each of the contours (assuming there's just two) to its own image. 
# Just fill with a '1'.
img1 = drawContours( blank.copy(), contours, 0, 1 )
img2 = drawContours( blank.copy(), contours, 1, 1 )

# now AND the two together
intersection = np.logical_and( img1, img2 )

# OR we could just add img1 to img2 and pick all points that sum to 2 (1+1=2):
intersection2 = (img1+img2)==2

If I look at intersection I will get an image that is 1 where the contours intersect and 0 everywhere else.

Alternatively you could fill in the entire contour (not just the contour but fill in the inside too) with drawContours( blank.copy(), contours, 0, 1, thickness=-1 ) and then the intersection image will contain the area of intersection between the contours.

Share:
19,620

Related videos on Youtube

Madman
Author by

Madman

Updated on June 04, 2022

Comments

  • Madman
    Madman almost 2 years

    I have 2 contours A and B and I want to check if they intersect. Both A and B are vectors of type cv::Point and are of different sizes

    To check for intersection, I was attempting to do a bitwise_and. This is throwing an exception because the inputs are of different size. How do I fix this ?

    Edit:

    The attached image should give a better idea about the issue. The car is tracked by a blue contour and the obstacle by a pink contour. I need to check for the intersection. enter image description here

  • Shravya Boggarapu
    Shravya Boggarapu over 4 years
    @Saikrishna use the grayscale values. If it is for visualization, draw contours at say 20... which is visible but not saturated. The intersection will be brighter (at 40 or more)
  • user202729
    user202729 over 4 years
    This is wrong for "compressed" contour, two contours may intersect even when they have no common vertices.
  • Reunanen
    Reunanen over 4 years
    @user202729 True. And the same holds for non-compressed 8-connected contours. But not for 4-connected.
  • Jeppe
    Jeppe about 4 years
    Doesn't drawContours only fill the outline? So you will get intersections between outlines? I had to add cv2.FILLED as argument: img2 = cv2.drawContours(blank.copy(), contours, 0, 1, cv2.FILLED).