# 如何统计一张黑色背景图像中的白色区域数量？

``````import cv2
import numpy as np
from PIL import Image
from glob import glob
import os

#二值化并获取图像内培养皿的圆形区域
gray_img = cv2.cvtColor(original_img,cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray_img,0,255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)
contours, _ = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for cont in contours:
(x, y), radius = cv2.minEnclosingCircle(cont)
ming=cv2.circle(original_img,(int(x),int(y)),int(radius-50), (0, 0, 255), 2)
roi = np.zeros(original_img.shape[:2], np.uint8)
roi = cv2.circle(roi,(int(x),int(y)), int(radius-50), 255, cv2.FILLED)
mask = np.ones_like(original_img) * 255

kernel1 = np.ones((5,5), np.uint8)
kernel2 = np.ones((3,3), np.uint8)#设置腐蚀和膨胀系数

ret, th1 = cv2.threshold(gray_img, 150, 255, cv2.THRESH_BINARY)
erosion = cv2.erode(th1, kernel1, iterations=1)
dilation = cv2.dilate(erosion, kernel2, iterations=1)#腐蚀和膨胀去噪点
cv2.imshow('erosion', erosion)
cv2.imshow('dilation',dilation)
cv2.waitKey(0)
``````

3 个回答

``````_, bin_img = cv2.threshold(dilation, 0, 1, cv2.THRESH_BINARY)

# 搜索图像中的连通区域
ret, labels, stats, centroid = cv2.connectedComponentsWithStats(bin_img, connectivity=4)

idx = 1
for stat in stats:
if (stat[2] - stat[0]) > bin_img.shape[0] / 2:
continue
cv2.rectangle(original_img_cbk, (stat[0], stat[1]), (stat[0] + stat[2], stat[1] + stat[3]), (0, 0, 255), 2)
cv2.putText(original_img_cbk, str(idx), (stat[0], stat[1] + 25), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 25, 25), 2)
idx += 1

plt.imshow(original_img_cbk)
plt.show()``````

###### 你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进