python - 如何确定轮廓是否已从Python/OpenCV中的边缘移开

标签 python opencv computer-vision logic

我正在使用两种不同的技术来创建跟踪系统,MOSSE是其中之一,我已经基于背景减去中的轮廓创建了边界框-我正在尝试找到将等高线显示在屏幕上的最佳方法在屏幕上知道它们是否已经远离图像边界(甚至距边界边缘一个像素),因此我可以将其用作边界框以从其开始进行MOSSE跟踪。

我当前正在遍历轮廓,需要对照上面的参数检查每个轮廓。

我考虑过使用pointPolygonTest并为框架的整个区域创建轮廓,检查轮廓是否在其中(没有点接触边界)。但是似乎无法弄清楚如何为整个框架创建轮廓,而且这可能效率很低。

while(1):
    ret, frame = cap.read()

    contour, heir = cv2.findContours(fgmask, cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)


    for cnt in contour:
        # and so on ...
        # This is where I will check the contour if it is touching frame boundary/edge

结果应该是,如果轮廓边缘未触及边框(两者之间没有像素间隙),我将得到输出通知我,以便可以为MOSSE添加边界框-帧中的每个轮廓都应发生这种情况。

如果我没有提供足够的细节,或者您需要澄清,请随时发表评论,我们将为您提供任何帮助。

最佳答案

这是另一个解决方案,使用您建议的轮廓。

我用OpenCV Wrapper library简化了矩形并包含了东西。转换为普通的OpenCV和Numpy并不难,只是有些乏味。

import cv2 as cv
import numpy as np
import opencv_wrapper as cvw

image = cv.imread("path/to/image")
gray = cvw.bgr2gray(image)
thresh = cvw.threshold_otsu(gray)

# Returns Contour object
contours = cvw.find_external_contours(thresh)

# Create a rectangle representing the boundary 1 pixel in.
boundary = cvw.Rect(1, 1, image.shape[1] - 2, image.shape[0] - 2)

for contour in contours:
    # Returns a Rect object
    rect = contour.bounding_rect
    if (
        rect.tl not in boundary
        or rect.tr not in boundary
        or rect.bl not in boundary
        or rect.br not in boundary
    ):
        continue

    # Create tracker
    cvw.rectangle(image, rect, cvw.Color.RED, 1)

cv.imshow("Image", np.hstack([image, cvw.gray2bgr(thresh)]))
cvw.wait_key(0)

披露:我是OpenCV Wrapper的作者。

关于python - 如何确定轮廓是否已从Python/OpenCV中的边缘移开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55486414/

相关文章:

python - 对 pandas 中相同的列名进行分组

python - 遍历 JSON 中的字符串数组

python - 重复处理,用字典排序

c++ - 如何使用 cmake 将两个库链接到我的程序?

c++ - 将 Bayer RGGB 转换为 CV iplimage (RGB)

python - 按python子列表中的值排序

python - 使用 OpenCV 检测图像上的 Blob

machine-learning - 如何在神经网络算法中一起处理文本和图像输入

algorithm - 如何在不同目录的多个图像中读取和运行算法?

c++ - 缩放和旋转模板匹配