问题

我有这个图像,我试图计算有多少个白色“球”

Imagem

我正在尝试下面的代码并得到这个结果

Result

 import cv2
import numpy as np
img = cv2.imread('MASK.jpg', cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img,(700,700))
img = cv2.subtract(255, img)

detector = cv2.SimpleBlobDetector_create()

 # Detect the blobs in the image
 keypoints = detector.detect(img)
 print(len(keypoints))


 imgKeyPoints = cv2.drawKeypoints(img, keypoints, np.array([]), (0,0,255), 
 cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

 cv2.imshow("Keypoints", imgKeyPoints)
 cv2.waitKey(0)

 cv2.destroyAllWindows()
 

  最佳答案

一些隔离blob的预处理可以帮助它们.这是一种方法:

  • 将图像转换为灰度
  • Otsu的门槛
  • morph打开以消除噪音
  • 找到轮廓和和blobs

转换为灰度后,我们Otsu的阈值得到二进制图像

接下来我们使用cv2.MORPH_ELLIPSE内核去除噪音并更好地分离blobs

接下来我们找到轮廓并总和blobs.请注意morph近似没有“分离”所有连接的blobs,所以我们使用轮廓区域过滤.如果blob大于某个最小阈值,我们将blob计算为双倍而不是单个.这是检测到的blobs

结果

Blobs:325

 import cv2
import numpy as np

image = cv2.imread('1.jpg')
mask = np.zeros(image.shape, dtype=np.uint8)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray,0,255,cv2.THRESH_OTSU + cv2.THRESH_BINARY)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7,7))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=5)

cnts = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

blobs = 0
for c in cnts:
    area = cv2.contourArea(c)
    cv2.drawContours(mask, [c], -1, (36,255,12), -1)
    if area > 13000:
        blobs += 2
    else:
        blobs += 1

print('blobs:', blobs)

cv2.imshow('thresh', thresh)
cv2.imshow('opening', opening)
cv2.imshow('image', image)
cv2.imshow('mask', mask)
cv2.waitKey()
 

  相同标签的其他问题

pythonimageopencvimage-processingcomputer-vision