python - 我想使用 opencv 删除边界

标签 python python-3.x opencv image-processing

我有这张原始图片:

image

然后我将以下代码应用到

  1. 将原始图像转换为 HSV 图像
  2. 然后使用 cv2.findContours() 我制作了一个包含所有轮廓的列表。

  3. 然后我删除了所有小于 30 的轮廓。

  4. 然后我得到了下图:

image

我想要的是从生成的图像中删除没有用的边界(叶子的外边界)。我只需要叶子的内部补丁。 这是我使用的代码。

import cv2
import numpy as np
img = cv2.imread('Apple___Blackrot30.JPG')
hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)     
lower_gr = np.array([25,0,0])
upper_gr = np.array([90,255,255])
mask = cv2.inRange(hsv,lower_gr,upper_gr)
mask=~mask   
res = cv2.bitwise_and(img,img,mask = mask)
blur = cv2.bilateralFilter(res,9,75,75)
im2,cont,_ = cv2.findContours(mask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
areas = [cv2.contourArea(each_conts) for each_conts in cont]
cont_counter = 0
for each_conts in areas:
    if each_conts < 30:
        cv2.fillPoly(im2, pts =[cont[cont_counter]], color=(0,0,0))
    if each_conts > 1024:
        cv2.drawContours(mask, cont[cont_counter], 0, (255,255,255), -1)    
    cont_counter+=1

cv2.imshow('cn',im2)

最佳答案

您可以使用 hierarchy of contours 的概念解决这个问题。但有一个警告,你所有的图像必须与问题中的图像相同。

我刚刚在您的代码中添加了一些额外的东西。

代码:

img2 = img.copy()
im2, cont, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

l = []
for e, h in enumerate(hierarchy[0]):
    #print (e, h[3])
    if h[3] == -1:
        l.append(e)

for i in l:
    if cv2.contourArea(cont[i]) < 1000:   
        cv2.drawContours(img2, [cont[i]], -1, (0, 255, 255), 2)

cv2.imshow('img2', img2)

结果:

enter image description here

hierarchy 返回一个数组,表示轮廓的父子关系。根据文档链接,

it as an array of four values : [Next, Previous, First_Child, Parent].

hierarchy 数组中,我扫描了 Parent 列(第 4 列)以查看它是否没有父轮廓(-1)和画了他们

关于python - 我想使用 opencv 删除边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51190561/

相关文章:

python - 将 tf.Dataset 拆分为测试和验证子集的规范方法是什么?

python-3.x - 在1个视频上输出2个功能

performance - calcOpticalFlowSF 的更快替代方案

python - 如何在 python igraph 中保留图中的顶点标签

python - Kivy 上的动画 Canvas 线

python - 高效的平行 3D 旋转

python - 在 Python 3.3 中是否有一种漂亮的 yield 方法?

opencv - 投影仪和 OpenCV

iphone - opencv 示例在 OpenFrameworks 中不起作用

python - 存储用于调用函数 Python 的数据