我在Python 2.7中使用cv2.connectedComponentsWithStats
来查找二进制图像中三个blob的质心。 (图片在In code it is img3
下面给出)。
在此图像中,存在三个白色bolb,因此质心的数量应仅为三个,但python显示8个质心值
[[ 307.08579803 95.31441513]
[ 511.51325364 141.06288981]
[ 259. 112.5 ]
[ 296.07169811 129.18490566]
[ 276. 140.5 ]
[ 225.19643047 237.16190375]
[ 189.21212121 271.6969697 ]
[ 187.58333333 285.83333333]]
每个bolbs的面积在最后一栏中给出
[[ 0 0 640 480 286024]
[ 260 65 100 68 3753]
[ 454 84 105 118 7696]
[ 259 112 1 2 2]
[ 277 117 34 23 265]
[ 276 140 1 2 2]
[ 168 173 114 128 9413]
[ 186 268 8 8 33]
[ 186 284 5 4 12]]
我的代码如下:
import numpy as np
import cv2
from PIL import Image
import matplotlib.pyplot as plt
import timeit
from skimage import morphology, measure
img = cv2.imread('left180.png')
lower_white = np.array([150,150,150], dtype=np.uint8)
upper_white = np.array([255,255,255], dtype=np.uint8)
binimg = cv2.inRange(img, lower_white, upper_white)
cv2.imshow('res',binimg)
binimg[binimg!=0] = 255
# flood fill background to find inner holes
holes = binimg.copy()
retval, image, mask, rect = cv2.floodFill(holes, None, (0, 0), 255)
# invert holes mask, bitwise or with img fill in holes
holes = cv2.bitwise_not(holes)
#cv2.imshow('holes',holes)
filled_holes = cv2.bitwise_or(binimg, holes)
cv2.imshow('filled holes', filled_holes)
imglab = morphology.label(filled_holes)
cv2.imshow('label',imglab)
cleaned = morphology.remove_small_objects(imglab, min_size=1264, connectivity=4)
#np.savetxt('cleaned.csv',cleaned,fmt='%.18g',delimiter=',')
cv2.imshow('clea',cleaned)
img3 = np.zeros((imglab.shape))
img3[cleaned > 0] = 255
img3= np.uint8(img3) #### here conversion of array into uint8 data conversion is important
### else cv2.connectedComponentsWithStats will show error.
#np.savetxt('img3.csv',img3,fmt='%.18g',delimiter=',')
nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(img3, connectivity=4)
sizes = stats[1:, -1];
#nb_components = nb_components - 1
cv2.imshow("centroid", img3)
centroids1 = centroids[1:nb_components]
print(centroids1)
print(stats)
cv2.waitKey(0)
为什么会出现这个问题?我想获得blob的质心,其面积大于1000像素。怎么做?