如何使用opencv和Python在ROI中找到轮廓? [英] How can I find contours inside ROI using opencv and Python?

查看:465
本文介绍了如何使用opencv和Python在ROI中找到轮廓?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在图像的特定区域中找到轮廓.是否可以只显示ROI内的轮廓,而不显示图像其余部分的轮廓?我在另一篇类似的文章中读到,我应该使用口罩,但是我认为我没有正确使用它.我是openCV和Python的新手,因此非常需要任何帮助.

Im trying to find contours in a specific area of the image. Is it possible to just show the contours inside the ROI and not the contours in the rest of the image? I read in another similar post that I should use a mask, but I dont think I used it correctly. Im new to openCV and Python, so any help is much appriciated.

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)

推荐答案

由于您自称是新手,所以我为您提供了解决方案和说明.

Since you claim to be a novice, I have worked out a solution along with an illustration.

请考虑以下内容作为您的原始图片:

Consider the following to be your original image:

假设以下红色区域是您要查找轮廓的感兴趣区域(ROI):

Assume that the following region in red is your region of interest (ROI), where you would like to find your contours:

首先,构造一个具有相同大小的黑色像素的图像. 它必须大小相同:

First, construct an image of black pixels of the same size. It MUST BE OF SAME size:

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

现在形成遮罩并突出显示ROI:

Now to form the mask and highlight the ROI:

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

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

Now mask the image above with your original image:

fin = cv2.bitwise_and(th,th,mask = mask)

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

Now use cv2.findContours() to find contours in the image above.

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

Then use cv2.drawContours() to draw contours on the original image. You will finally obtain the following:

也许还有更好的方法,但是这样做是为了让您了解OpenCV中专门用于屏蔽

There might be better methods as well, but this was done so as to get you aware of the bitwise AND operation availabe in OpenCV which is exclusively used for masking

这篇关于如何使用opencv和Python在ROI中找到轮廓?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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