【发布时间】:2021-12-23 03:41:12
【问题描述】:
我还在学习图像遮罩。
我正在尝试计算图像中红点的数量。
问题是,有些 blob 没有满,所以它不计算所有 blob,例如在这个特定的图像中,它不计算数字 6 和 9。(假设左上角是 1)
如何改进掩蔽过程以获得更准确的 blob?
掩码:
import cv2, os
import numpy as np
os.chdir('C:\Program Files\Python\projects\Blob')
#Get image input
image_input = cv2.imread('realbutwithacrylic.png')
image_input = np.copy(image_input)
rgb = cv2.cvtColor(image_input, cv2.COLOR_BGR2RGB)
#Range of color wanted
lower_red = np.array([125, 1, 0])
upper_red = np.array([200, 110, 110])
#Masking the Image
first_mask = cv2.inRange(rgb, lower_red, upper_red)
#Output
cv2.imshow('first_mask', first_mask)
cv2.waitKey()
使用 Blob 计数器屏蔽代码
import cv2, os
import numpy as np
#Some Visual Studio Code bullshit because it cant find the image????
os.chdir('C:\Program Files\Python\projects\Blob')
#Get image input
image_input = cv2.imread('realbutwithacrylic.png')
image_input = np.copy(image_input)
rgb = cv2.cvtColor(image_input, cv2.COLOR_BGR2RGB)
#Range of color wanted
lower_red = np.array([125, 1, 0])
upper_red = np.array([200, 110, 110])
#Masking the Image
first_mask = cv2.inRange(rgb, lower_red, upper_red)
#Initial masking counter
cv2.imshow('first_mask', first_mask)
cv2.waitKey()
#Blob Counter
thresh = cv2.threshold(first_mask,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]
#Couting the blobs
blobs = 0
for c in cnts:
area = cv2.contourArea(c)
cv2.drawContours(first_mask, [c], -1, (36,255,12), -1)
if area > 13000:
blobs += 2
else:
blobs += 1
#Blob Number Output
print('blobs:', blobs)
#Masking Output
cv2.imshow('thresh', thresh)
cv2.imshow('opening', opening)
cv2.imshow('image', image_input)
cv2.imshow('mask', first_mask)
cv2.waitKey()
【问题讨论】:
-
您可以先用
close填充对象内部的空隙,然后再用open。看看这个opencv24-python-tutorials.readthedocs.io/en/latest/py_tutorials/…。最后使用内核大小来获得更好的结果(我会使用目标圆半径的 1/4 或 1/5 的圆(以像素为单位,但只是直观地) -
我认为您可能还需要一些局部对比度归一化来帮助在有点模糊的区域中显示红色。
-
@UlisesBussi 感谢这使 6 号可数,但 9 仍然是一个问题。可能是图像,因为存储被丙烯酸面板覆盖,这确实与图像质量有关。
标签: python numpy opencv image-processing