我正在尋找一個適當的解決方案,如何在此影像中計算粒子并測量它們的大小:

最后,我必須獲得粒子坐標和面積平方的串列。在互聯網上進行了一些搜索后,我意識到有 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()
我們可能會得到如下資訊:

而且...我對結果并不滿意。一些清晰可見的粒子不包括在內,另一方面,一些懷疑的強度波動已經被計算在內。我現在正在玩不同的過濾器設定,但感覺是錯誤的。
如果有人知道如何改進我的解決方案,請分享。
uj5u.com熱心網友回復:
由于粒子是白色的,背景是黑色的,我們可以使用 Kmeans 顏色量化將影像分割成兩組cluster=2。這將使我們能夠輕松地區分粒子和背景。由于粒子可能非常小,我們應該盡量避免模糊、膨脹或任何可能改變粒子輪廓的形態學操作。這是一種方法:
Kmeans 顏色量化。我們使用兩個聚類、灰度和 Otsu 閾值執行 Kmeans 以獲得二值影像。
過濾掉超微小的噪音。接下來我們找到輪廓,使用輪廓區域過濾去除微小的噪聲,并收集每個粒子
(x, y)坐標及其區域。我們通過“填充”這些輪廓來去除二進制掩碼上的微小顆粒,從而有效地擦除它們。將蒙版應用到原始影像上。現在我們將過濾后的蒙版按位加到原始影像上以突出顯示粒子簇。
Kmeans 與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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/473337.html
標籤:Python 图片 opencv 图像处理 计算机视觉
