2011-12-18 268 views
9

我有2个轮廓A和B,我想检查它们是否相交。 A和B两者都是类型CV点::向量和是不同尺寸OpenCV检测轮廓相交

的要检查相交,我试图做bitwise_and。这是抛出一个异常,因为输入的大小不同。我该如何解决 ?

编辑:

所附的图像应该给有关问题的一个更好的主意。汽车由蓝色轮廓跟踪,而障碍物由粉红色轮廓跟踪。我需要检查路口。 enter image description here

回答

11

一个简单但可能不是最有效的方法是使用drawContours来创建两个图像:一个具有汽车轮廓,另一个具有障碍轮廓。

然后and他们在一起,任何仍然是积极的点将是交点。

一些伪代码(我使用Python接口,这样就不会得到C++语法正确的,但它应该是非常简单,你转换):

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 

如果我看intersection我会得到一个图像是等高线相交的地方,而其他地方是0。

另外,您可以填写整个轮廓(不只是轮廓,但在里面太满)与drawContours(blank.copy(), contours, 0, 1, thickness=-1)然后intersection图像将包含轮廓之间的交叉区域。

+0

谢谢!似乎工作很好。 – Madman 2011-12-19 07:56:19

0

如果您首先使用几乎任何一致的排序标准对您的矢量进行排序,那么您可以直接在矢量上使用std::set_intersection。如果轮廓比图像大小短,这可能比公认的答案更快。

0

我发现Clipper库对于这些目的非常有用。 (将cv::Point的向量转换为Clipper Path对象可以直接进行。)