Madman - 4 months ago 86

C++ Question

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.

Answer

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.