在 python 中检测图像中的彩色点?

Detect colorful dots in image in python?

我正在尝试检测 white/gray 背景上的彩色圆点。这些点是 3 种不同大小的不同颜色(黄色、紫色、蓝色)。这是原始图像:

我将图像转换为 HSV 并找到每个图像的下限和上限,然后应用轮廓检测​​来找到那些点。以下代码检测到大部分点:

import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('image1_1.png')

hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

lower_yellow = np.array([22,25,219])
upper_yellow = np.array([25,75,225])

lower_purple = np.array([141,31,223])
upper_purple = np.array([143,83,225])

lower_blue = np.array([92,32,202])
upper_blue = np.array([96,36,208])

mask_blue = cv2.inRange(hsv, lower_blue, upper_blue)
mask_purple = cv2.inRange(hsv, lower_purple, upper_purple)
mask_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow)

res_blue = cv2.bitwise_and(img,img, mask=mask_blue)
res_purple = cv2.bitwise_and(img,img, mask=mask_purple)
res_yellow = cv2.bitwise_and(img,img, mask=mask_yellow)

gray_blue = cv2.cvtColor(res_blue, cv2.COLOR_BGR2GRAY)
gray_purple = cv2.cvtColor(res_purple, cv2.COLOR_BGR2GRAY)
gray_yellow = cv2.cvtColor(res_yellow, cv2.COLOR_BGR2GRAY)

_,thresh_blue = cv2.threshold(gray_blue,10,255,cv2.THRESH_BINARY)
_,thresh_purple = cv2.threshold(gray_purple,10,255,cv2.THRESH_BINARY)
_,thresh_yellow = cv2.threshold(gray_yellow,10,255,cv2.THRESH_BINARY)

contours_blue, hierarhy1 = cv2.findContours(thresh_blue,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
contours_purple, hierarhy2 = cv2.findContours(thresh_purple,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
contours_yellow, hierarhy3 = cv2.findContours(thresh_yellow,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

result = img.copy()
cv2.drawContours(result, contours_blue, -1, (0, 0, 255), 2)
cv2.drawContours(result, contours_purple, -1, (0, 0, 255), 2)
cv2.drawContours(result, contours_yellow, -1, (0, 0, 255), 2)
cv2.imwrite("_allContours.jpg", result)

检测到的轮廓如下:

问题是有些彩色点没有被检测到。我知道通过微调颜色 运行ges(下部和上部)可以检测到更多点。但这非常耗时,并且不能推广到相似的图像。例如,下图看起来与上面的第一张图片相似,并且具有相同的彩色点,但背景略有不同,一旦我通过上面的代码 运行 它甚至无法检测到其中一个点。我在正确的轨道上吗?是否有更可扩展和更可靠的解决方案,不需要调整颜色参数来解决这个问题?这是我试过的另一张图片:

我建议在 Python/OpenCV

中简单地使用 adaptiveThreshold
import cv2
import numpy as np

# read image
img = cv2.imread("dots.png")

# convert img to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# do adaptive threshold on gray image
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 25, 6)

# write results to disk
cv2.imwrite("dots_thresh.jpg", thresh)

# display it
cv2.imshow("thresh", thresh)
cv2.waitKey(0)