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

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:

25ad761e715738c56c2e44f40d86d74c.png

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

0911a8f20891f90e662976339c2b4026.png

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

f2f403e97372978d72d4eed39d6c2957.png

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

aff86f6801a3e819d34c56e6112502d6.png

Now mask the image above with your original image:

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

f189ab8ab4733a186c93f53c6fb3ff09.png

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

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

0a32c7de5d35c41f92b4d78db0794192.png

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值