如何检测由较小轮廓组成的较大轮廓?

时间:2018-01-07 05:09:37

标签: python opencv image-processing opencv-contour cv2

sample image

我对图像处理很陌生。我正在使用opencv和python。 我熟悉寻找轮廓的常规方法,但在这种情况下,我想忽略每个方形作为轮廓,但想要在每个所述形状上进行轮廓,如图所示。

目前在阈值处理后,我得到每个方块的轮廓。 opencv库中是否有任何简单的功能来检测这些整个大型形状而不是小方块。

1 个答案:

答案 0 :(得分:3)

由于您想要提取黄色矩形区域,所以:

1. Read
2. Exrtact green channel 
3. Do morph-close-op and threshold
4. Findcontours and filter by Area

enter image description here

#!/usr/bin/python3
# 2018.01.07 14:04:18 CST
# 2018.01.07 14:20:15 CST

import cv2 

## 1. Read
img = cv2.imread("img01.png")

## 2. Exrtact green channel
g = img[...,1]

## 3. Do morph-close-op and Threshold
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
morphed = cv2.morphologyEx(g,cv2.MORPH_CLOSE, kernel)

th, threshed = cv2.threshold(morphed, 100, 255, cv2.THRESH_OTSU)

## 4. Findcontours and filter by Area
cnts = cv2.findContours(threshed, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2]

canvas = img.copy()

AREA = img.shape[0]*img.shape[1]/20
for cnt in cnts:
    if cv2.contourArea(cnt) < AREA:
        cv2.drawContours(canvas, [cnt], -1, (0,255,0), 2, cv2.LINE_AA)

## 
cv2.imwrite("res.png", canvas)