我正在处理具有形状的图像,并且试图计算具有1个孔的对象和具有2个孔的对象.
我找到了有关的信息,但是它在MATLAB Segment out those objects that have holes in it中
他们使用了Euler特性,我知道在Python中存在skimage库,但是我不能使用它.
我也找到了一些代码,但我听不懂. http://www.cis.rit.edu/class/simg782/homework/hw3/hw3solutions.pdf第16.页
PRO hw3 4,A,LA,LC,count
;Find all the holes
Ac=A EQ 0
LC=label region(Ac,/ALL)
;Construct an array with the holes filled in
Afill=(A GT 0) OR (LC GT 1)
;Display the arrays
sa=size(A,/dim)
window,/free,xsize=sa[0],ysize=sa[1]
tvlct,rr,gg,bb,/get
tek color
TV,Afill
window,ysize=sa[1]
TV,LC
;Count the objects with holes. First we
;find all the objects and then match up
;the object labels and the hole labels.
LA=label region(Afill)
window,LA
ha=histogram(LA)
ia=where(ha ge 0)
print,format=’("Objects",3x,"Count",/,(i2,5x,i7))’,$
[transpose(ia),transpose(ha[ia])]
;Each element of ia corresponds to a filled
;object. Object k is labeled ia[k]. For each
;object that is not background,;determine whether it has holes.
c=0
print
print,"k ia[k] N C"
For k=1,n elements(ia)-1 DO BEGIN
B=bytarr(sa[0],sa[1]); Make an array with one object
ik=Where(LA eq ia[k]); ;Fill in the object
IF MIN(ik) GE 0 THEN B[ik]=1
;Now see if any of the object pixels match the
;hole image LC. Counts if one or more holes.
IF MAX(B AND (LC GT 0)) GT 0 THEN c++
print,[k,ia[k],n elements(ik),c],format=’(I2,1x,I2,I5,2x,I1)’
END
Print,’Number of objects with one or more holes=’,count
tvlct,bb
END
IDL> hw3 4,count
想法是计算具有1个孔的对象和具有2个孔的对象,并突出显示其边缘.
“一个孔的对象数:2”
“带有两个孔的对象数:4”
这是我所拥有的,我使用一个简单的cv2.HoughCircles做到了:
最佳答案
Contour Hierarchy可用于根据对象的孔数对对象进行计数.想象一下,您有100个空的各种大小的盒子,从一个大冰箱盒到一个小首饰盒.您要存储所有100个盒子,因此将一些盒子放在其他较大的盒子中.您还希望以后能够找到这些框,因此可以保留其中一个框的列表.等高线的工作方式相同,此列表称为层次结构.
原文链接:https://www.f2er.com/python/533268.html查找轮廓和层次结构:
img = cv2.imread('/home/stephen/Desktop/test.png',0)
_,contours,hierarchy = cv2.findContours(img,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)
接下来,遍历每个轮廓以查找其中是否有轮廓
max_num = np.amax(hierarchy) +1
for c,h in zip(contours,hierarchy[0]):
# If there is at least one interior contour,find out how many there are
if h[2] != -1:
# Make sure it's not the 'zero' contour
if h[0] == -1:
num_interior_contours = max_num - h[2]
else: num_interior_contours = h[0]-h[2]
else: num_interior_contours = 0
绘制或计算内部具有其他轮廓的轮廓的数量:
if num_interior_contours == 1:
cv2.drawContours(img_color,[c],-1,(255,255),2)
# Outline the contour in green if there are two holes.
if num_interior_contours == 2:
cv2.drawContours(img_color,(0,255,0),2)