Wil*_*vis 6 python opencv image image-processing computer-vision
我正在寻找一个正确的解决方案,如何在此图像中计算粒子数量并测量其大小:
最后我必须获得粒子坐标和面积平方的列表。经过在互联网上的一些搜索,我发现有 3 种粒子检测方法:
看看不同的项目,我将它们组合起来组装了一些代码。
import pylab
import cv2
import numpy as np
Run Code Online (Sandbox Code Playgroud)
高斯模糊和阈值化
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)
Run Code Online (Sandbox Code Playgroud)
过滤小物体
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
Run Code Online (Sandbox Code Playgroud)
生成用于填充孔和测量的轮廓。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)))
Run Code Online (Sandbox Code Playgroud)
为了进行自检,如果我们在原始图像上绘制这些坐标
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()
Run Code Online (Sandbox Code Playgroud)
我们可能会得到类似下面的内容:
而且...我对结果不太满意。一些清晰可见的颗粒没有被包括在内,另一方面,一些怀疑强度波动是否被计算在内。我现在正在使用不同的过滤器设置,但感觉这是错误的。
如果有人知道如何改进我的解决方案,请分享。
由于粒子为白色,背景为黑色,我们可以使用 Kmeans 颜色量化将图像分割为两组,其中cluster=2
. 这将使我们能够轻松区分粒子和背景。由于粒子可能非常小,我们应该尽量避免模糊、膨胀或任何可能改变粒子轮廓的形态操作。这是一种方法:
K表示颜色量化。我们使用两个聚类、灰度和 Otsu 阈值执行 Kmeans,以获得二值图像。
过滤掉超微小的噪音。接下来,我们找到轮廓,使用轮廓区域过滤去除微小的噪声规格,并收集每个粒子的(x, y)
坐标及其面积。我们通过“填充”这些轮廓来有效地擦除二元掩模上的微小颗粒。
将蒙版应用到原始图像上。现在我们将过滤后的蒙版按位加到原始图像上以突出显示粒子簇。
K均值与clusters=2
结果
Number of particles: 204
Average particle size: 30.537
Run Code Online (Sandbox Code Playgroud)
代码
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()
Run Code Online (Sandbox Code Playgroud)