Joc*_*240 5 python image-processing python-3.x
我正在处理具有形状的图像,并且我正在尝试计算具有 1 个孔的对象和具有 2 个孔的对象。

我找到了关于它的信息,但它是在 MATLAB 中将 那些有孔的对象分割出来 他们使用了 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,/free,xsize=sa[0],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,/free,xsize=sa[0],ysize=sa[1]
TV,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,3x,I5,2x,I1)’
END
Print,’Number of objects with one or more holes=’,count
tvlct,rr,gg,bb
END
IDL> hw3 4,A,LA,LC,count
Run Code Online (Sandbox Code Playgroud)
这个想法是计算具有 1 个孔的对象和具有 2 个孔的对象,并突出显示它们的边缘。
“一个孔的物体数量:2”
“有两个孔的物体数量:4”
这是我所拥有的,我用一个简单的方法做到了cv2.HoughCircles:

轮廓层次结构可用于根据对象的孔数来计数对象。想象一下,您有 100 个不同尺寸的空盒子,从大冰箱盒到小珠宝盒。您想要存储所有 100 个盒子,因此您将一些盒子放入其他较大的盒子中。您还希望稍后能够找到这些盒子,因此您保留了哪个盒子位于哪个盒子内的列表。轮廓的工作方式相同,这个列表称为层次结构。
要查找轮廓和层次结构:
img = cv2.imread('/home/stephen/Desktop/test.png', 0)
_, contours, hierarchy = cv2.findContours(img,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)
Run Code Online (Sandbox Code Playgroud)
接下来,迭代每个轮廓以查找其内部是否有任何轮廓
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
Run Code Online (Sandbox Code Playgroud)
绘制或计算内部有另一个轮廓的轮廓数:
if num_interior_contours == 1:
cv2.drawContours(img_color, [c], -1, (255,0,255), 2)
# Outline the contour in green if there are two holes.
if num_interior_contours == 2:
cv2.drawContours(img_color, [c], -1, (0,255,0), 2)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1987 次 |
| 最近记录: |