import cv2
import glob
def count_white_particles(image):
# 转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 对图像进行二值化
_, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
# 去除噪声
thresh = cv2.medianBlur(thresh, 5)
# 查找图像中的轮廓
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 绘制颗粒并计算数量
count = 0
for contour in contours:
area = cv2.contourArea(contour)
if area > 100: # 过滤掉过小的颗粒
count += 1
return count
img_paths = glob.glob('folder/*.jpg')
for img_path in img_paths:
# 读取图片
img = cv2.imread(img_path)
# 计算白色颗粒数量
count = count_white_particles(img)
# 显示结果
cv2.imshow('Image', img)
cv2.putText(img, "Number of white particles: " + str(count), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
cv2.waitKey(0)
# 输出颗粒数量
print("Number of white particles in", img_path, ":", count)
一个范围罢了,决定你照片看起来模糊还是清晰