如何使用opencv和Python在ROI中找到轮廓?

agr*_*rom 3 python opencv roi

我试图找到图像特定区域的轮廓.是否可以只显示ROI内部的轮廓而不是图像其余部分的轮廓?我在另一篇类似的帖子中读到我应该使用面具,但我不认为我正确使用它.我是openCV和Python的新手,所以任何帮助都很受欢迎.

import numpy as np
import cv2

cap = cv2.VideoCapture('size4.avi')
x, y, w, h= 150, 50, 400 ,350
roi = (x, y, w, h)

while(True): 
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    _, thresh = cv2.threshold(gray, 127, 255, 0)
    im2, contours, hierarchy = cv2.findContours(thresh,    cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

    roi = cv2.rectangle(frame, (x,y), (x+w, y+h), (0,0,255), 2)
    mask = np.zeros(roi.shape,np.uint8)
    cv2.drawContours(mask, contours, -1, (0,255,0), 3)

    cv2.imshow('img', frame)
Run Code Online (Sandbox Code Playgroud)

Tom*_* M. 6

为了在 Python 中设置 ROI,可以使用标准 NumPy 索引,例如在本例中

因此,要选择正确的 ROI,您不使用 cv2.rectangle 函数(即用于绘制矩形),而是执行以下操作:

 _, thresh = cv2.threshold(gray, 127, 255, 0)
 roi = thresh[x:(x+w), y:(y+h)]
 im2, contours, hierarchy = cv2.findContours(roi, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
Run Code Online (Sandbox Code Playgroud)

  • 您可以将矩形的偏移量传递给 findContours,以便检索到的轮廓点参考原始图像 (2认同)
  • 文档:http://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=findcontours 说该函数的最后一个参数是一个指定偏移量的元组;即:`im2,轮廓,层次= cv2.findContours(roi, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE, (x, y))` (2认同)

Jer*_*uke 6

既然你声称自己是新手,我已经制定了解决方案和插图.

请考虑以下内容作为原始图像:

在此输入图像描述

假设以下红色区域是您感兴趣的区域(ROI),您可以在其中找到您的轮廓:

在此输入图像描述

首先,构建相同大小的黑色像素的图像.它必须是相同的大小:

black = np.zeros((img.shape[0], img.shape[1], 3), np.uint8) #---black in RGB
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

现在形成面具并突出投资回报率:

black1 = cv2.rectangle(black,(185,13),(407,224),(255, 255, 255), -1)   #---the dimension of the ROI
gray = cv2.cvtColor(black,cv2.COLOR_BGR2GRAY)               #---converting to gray
ret,b_mask = cv2.threshold(gray,127,255, 0)                 #---converting to binary image
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

现在用原始图像掩盖上面的图像:

fin = cv2.bitwise_and(th,th,mask = mask)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

现在用于cv2.findContours()查找上图中的轮廓.

然后用于cv2.drawContours()在原始图像上绘制轮廓.您将最终获得以下内容:

在此输入图像描述

可能还有更好的方法,但这样做是为了让您了解 OpenCV中可用的按位AND操作,该操作专门用于屏蔽

  • 我给出了这个解决方案,因为你想知道如何在图像中执行掩蔽.关键是要有效地使用函数`cv2.bitwise_and()` (2认同)