使用 Python OpenCV 进行粒子检测
Particle detection with Python OpenCV
我正在寻找一个合适的解决方案来计算这张图片中的粒子数量并测量它们的大小:
最后我必须得到粒子坐标和面积平方的列表。在互联网上搜索后,我发现有 3 种粒子检测方法:
- 斑点
- 轮廓
- connectedComponentsWithStats
查看不同的项目,我组合了一些代码。
import pylab
import cv2
import numpy as np
高斯模糊和阈值处理
original_image = cv2.imread(img_path)
img = original_image
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = cv2.GaussianBlur(img, (5, 5), 0)
img = cv2.blur(img, (5, 5))
img = cv2.medianBlur(img, 5)
img = cv2.bilateralFilter(img, 6, 50, 50)
max_value = 255
adaptive_method = cv2.ADAPTIVE_THRESH_GAUSSIAN_C
threshold_type = cv2.THRESH_BINARY
block_size = 11
img_thresholded = cv2.adaptiveThreshold(img, max_value, adaptive_method, threshold_type, block_size, -3)
过滤小物体
min_size = 4
nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(img, connectivity=8)
sizes = stats[1:, -1]
nb_components = nb_components - 1
# for every component in the image, you keep it only if it's above min_size
for i in range(0, nb_components):
if sizes[i] < min_size:
img[output == i + 1] = 0
生成用于填充孔和测量的轮廓。 pos_list
和 size_list
是我们要找的
contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
pos_list = []
size_list = []
for i in range(len(contours)):
area = cv2.contourArea(contours[i])
size_list.append(area)
(x, y), radius = cv2.minEnclosingCircle(contours[i])
pos_list.append((int(x), int(y)))
对于自检,如果我们将这些坐标绘制在原始图像上
pts = np.array(pos_list)
pylab.figure(0)
pylab.imshow(original_image)
pylab.scatter(pts[:, 0], pts[:, 1], marker="x", color="green", s=5, linewidths=1)
pylab.show()
我们可能会得到如下内容:
还有...我对结果不是很满意。一些清晰可见的粒子不包括在内,另一方面,一些可疑的强度波动已经被计算在内。我现在正在玩不同的过滤器设置,但感觉是错误的。
如果有人知道如何改进我的解决方案,请分享。
由于粒子是白色的,背景是黑色的,我们可以使用Kmeans Color Quantization将图像分割成cluster=2
的两组。这将使我们能够轻松区分粒子和背景。由于粒子可能非常小,我们应该尽量避免模糊、膨胀或任何可能改变粒子轮廓的形态学操作。这是一个方法:
Kmeans颜色量化。我们用两个簇进行Kmeans,灰度,然后Otsu的阈值得到二值图像。
过滤掉极小的噪声接下来我们找到轮廓,使用轮廓区域过滤去除微小的噪声规格,并收集每个粒子(x, y)
坐标及其面积。我们通过“填充”这些轮廓来有效地擦除它们,从而去除二元掩模上的微小颗粒。
将蒙版应用到原始图像上。现在我们bitwise-and将过滤后的蒙版应用到原始图像上以突出显示粒子簇。
K 均值为 clusters=2
结果
Number of particles: 204
Average particle size: 30.537
代码
import cv2
import numpy as np
import pylab
# Kmeans
def kmeans_color_quantization(image, clusters=8, rounds=1):
h, w = image.shape[:2]
samples = np.zeros([h*w,3], dtype=np.float32)
count = 0
for x in range(h):
for y in range(w):
samples[count] = image[x][y]
count += 1
compactness, labels, centers = cv2.kmeans(samples,
clusters,
None,
(cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10000, 0.0001),
rounds,
cv2.KMEANS_RANDOM_CENTERS)
centers = np.uint8(centers)
res = centers[labels.flatten()]
return res.reshape((image.shape))
# Load image
image = cv2.imread('1.png')
original = image.copy()
# Perform kmeans color segmentation, grayscale, Otsu's threshold
kmeans = kmeans_color_quantization(image, clusters=2)
gray = cv2.cvtColor(kmeans, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
# Find contours, remove tiny specs using contour area filtering, gather points
points_list = []
size_list = []
cnts, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2:]
AREA_THRESHOLD = 2
for c in cnts:
area = cv2.contourArea(c)
if area < AREA_THRESHOLD:
cv2.drawContours(thresh, [c], -1, 0, -1)
else:
(x, y), radius = cv2.minEnclosingCircle(c)
points_list.append((int(x), int(y)))
size_list.append(area)
# Apply mask onto original image
result = cv2.bitwise_and(original, original, mask=thresh)
result[thresh==255] = (36,255,12)
# Overlay on original
original[thresh==255] = (36,255,12)
print("Number of particles: {}".format(len(points_list)))
print("Average particle size: {:.3f}".format(sum(size_list)/len(size_list)))
# Display
cv2.imshow('kmeans', kmeans)
cv2.imshow('original', original)
cv2.imshow('thresh', thresh)
cv2.imshow('result', result)
cv2.waitKey()
我正在寻找一个合适的解决方案来计算这张图片中的粒子数量并测量它们的大小:
最后我必须得到粒子坐标和面积平方的列表。在互联网上搜索后,我发现有 3 种粒子检测方法:
- 斑点
- 轮廓
- connectedComponentsWithStats
查看不同的项目,我组合了一些代码。
import pylab
import cv2
import numpy as np
高斯模糊和阈值处理
original_image = cv2.imread(img_path)
img = original_image
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = cv2.GaussianBlur(img, (5, 5), 0)
img = cv2.blur(img, (5, 5))
img = cv2.medianBlur(img, 5)
img = cv2.bilateralFilter(img, 6, 50, 50)
max_value = 255
adaptive_method = cv2.ADAPTIVE_THRESH_GAUSSIAN_C
threshold_type = cv2.THRESH_BINARY
block_size = 11
img_thresholded = cv2.adaptiveThreshold(img, max_value, adaptive_method, threshold_type, block_size, -3)
过滤小物体
min_size = 4
nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(img, connectivity=8)
sizes = stats[1:, -1]
nb_components = nb_components - 1
# for every component in the image, you keep it only if it's above min_size
for i in range(0, nb_components):
if sizes[i] < min_size:
img[output == i + 1] = 0
生成用于填充孔和测量的轮廓。 pos_list
和 size_list
是我们要找的
contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
pos_list = []
size_list = []
for i in range(len(contours)):
area = cv2.contourArea(contours[i])
size_list.append(area)
(x, y), radius = cv2.minEnclosingCircle(contours[i])
pos_list.append((int(x), int(y)))
对于自检,如果我们将这些坐标绘制在原始图像上
pts = np.array(pos_list)
pylab.figure(0)
pylab.imshow(original_image)
pylab.scatter(pts[:, 0], pts[:, 1], marker="x", color="green", s=5, linewidths=1)
pylab.show()
我们可能会得到如下内容:
还有...我对结果不是很满意。一些清晰可见的粒子不包括在内,另一方面,一些可疑的强度波动已经被计算在内。我现在正在玩不同的过滤器设置,但感觉是错误的。
如果有人知道如何改进我的解决方案,请分享。
由于粒子是白色的,背景是黑色的,我们可以使用Kmeans Color Quantization将图像分割成cluster=2
的两组。这将使我们能够轻松区分粒子和背景。由于粒子可能非常小,我们应该尽量避免模糊、膨胀或任何可能改变粒子轮廓的形态学操作。这是一个方法:
Kmeans颜色量化。我们用两个簇进行Kmeans,灰度,然后Otsu的阈值得到二值图像。
过滤掉极小的噪声接下来我们找到轮廓,使用轮廓区域过滤去除微小的噪声规格,并收集每个粒子
(x, y)
坐标及其面积。我们通过“填充”这些轮廓来有效地擦除它们,从而去除二元掩模上的微小颗粒。将蒙版应用到原始图像上。现在我们bitwise-and将过滤后的蒙版应用到原始图像上以突出显示粒子簇。
K 均值为 clusters=2
结果
Number of particles: 204
Average particle size: 30.537
代码
import cv2
import numpy as np
import pylab
# Kmeans
def kmeans_color_quantization(image, clusters=8, rounds=1):
h, w = image.shape[:2]
samples = np.zeros([h*w,3], dtype=np.float32)
count = 0
for x in range(h):
for y in range(w):
samples[count] = image[x][y]
count += 1
compactness, labels, centers = cv2.kmeans(samples,
clusters,
None,
(cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10000, 0.0001),
rounds,
cv2.KMEANS_RANDOM_CENTERS)
centers = np.uint8(centers)
res = centers[labels.flatten()]
return res.reshape((image.shape))
# Load image
image = cv2.imread('1.png')
original = image.copy()
# Perform kmeans color segmentation, grayscale, Otsu's threshold
kmeans = kmeans_color_quantization(image, clusters=2)
gray = cv2.cvtColor(kmeans, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
# Find contours, remove tiny specs using contour area filtering, gather points
points_list = []
size_list = []
cnts, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2:]
AREA_THRESHOLD = 2
for c in cnts:
area = cv2.contourArea(c)
if area < AREA_THRESHOLD:
cv2.drawContours(thresh, [c], -1, 0, -1)
else:
(x, y), radius = cv2.minEnclosingCircle(c)
points_list.append((int(x), int(y)))
size_list.append(area)
# Apply mask onto original image
result = cv2.bitwise_and(original, original, mask=thresh)
result[thresh==255] = (36,255,12)
# Overlay on original
original[thresh==255] = (36,255,12)
print("Number of particles: {}".format(len(points_list)))
print("Average particle size: {:.3f}".format(sum(size_list)/len(size_list)))
# Display
cv2.imshow('kmeans', kmeans)
cv2.imshow('original', original)
cv2.imshow('thresh', thresh)
cv2.imshow('result', result)
cv2.waitKey()