OpenCV检测轮廓交点 [英] OpenCV detect contours intersection

查看:149
本文介绍了OpenCV检测轮廓交点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个轮廓A和B,我想检查它们是否相交. A和B都是cv :: Point类型的向量,并且具有不同的大小

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

为检查交叉点,我试图做一个 bitwise_and .由于输入的大小不同,因此引发了异常.我该如何解决 ?

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 ?

附加的图像应该可以更好地解决此问题.蓝色轮廓跟踪汽车,粉红色轮廓跟踪障碍物.我需要检查路口.

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.

推荐答案

一种简单但也许不是最有效(??)的方法是使用drawContours来创建两个图像:一个具有汽车的轮廓,另一个具有汽车的轮廓.一个带有障碍物轮廓的东西.

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.

然后and将它们放在一起,任何仍为正的点将成为相交点.

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

一些伪代码(我使用Python接口,因此无法正确使用C ++语法,但是对于您而言,它应该足够简单):

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

如果我查看intersection,将得到的图像是等高线相交的1和其他任何地方的0.

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

或者,您可以用drawContours( blank.copy(), contours, 0, 1, thickness=-1 )填充整个轮廓(不仅是轮廓,还要填充内部),然后intersection图像将包含轮廓之间的交点区域

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.

这篇关于OpenCV检测轮廓交点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆