我有这张原始图片:
然后我将以下代码应用到
- 将原始图像转换为 HSV 图像
然后使用
cv2.findContours()
我制作了一个包含所有轮廓的列表。然后我删除了所有小于 30 的轮廓。
- 然后我得到了下图:
我想要的是从生成的图像中删除没有用的边界(叶子的外边界)。我只需要叶子的内部补丁。 这是我使用的代码。
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)
结果:
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/