使用python和OpenCV对图像上的单元格进行计数
我正试图写一个算法来计算图像上的点(细胞) 以下是我到目前为止所做的脚本:使用python和OpenCV对图像上的单元格进行计数,python,image,opencv,counting,Python,Image,Opencv,Counting,我正试图写一个算法来计算图像上的点(细胞) 以下是我到目前为止所做的脚本: import numpy as np import cv2 import os for dirname in os.listdir("images/"): for filename in os.listdir("images/" + dirname + "/"): # Image read img = cv2.imread("images/" + dirname + "/"
import numpy as np
import cv2
import os
for dirname in os.listdir("images/"):
for filename in os.listdir("images/" + dirname + "/"):
# Image read
img = cv2.imread("images/" + dirname + "/" + filename, 0)
# Denoising
denoisedImg = cv2.fastNlMeansDenoising(img);
# Threshold (binary image)
# thresh – threshold value.
# maxval – maximum value to use with the THRESH_BINARY and THRESH_BINARY_INV thresholding types.
# type – thresholding type
th, threshedImg = cv2.threshold(denoisedImg, 200, 255,cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU) # src, thresh, maxval, type
# Perform morphological transformations using an erosion and dilation as basic operations
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
morphImg = cv2.morphologyEx(threshedImg, cv2.MORPH_OPEN, kernel)
# Find and draw contours
contours, hierarchy = cv2.findContours(morphImg, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contoursImg = cv2.cvtColor(morphImg, cv2.COLOR_GRAY2RGB)
cv2.drawContours(contoursImg, contours, -1, (255,100,0), 3)
cv2.imwrite("results/" + dirname + "/" + filename + "_result.tif", contoursImg)
textFile = open("results/results.txt","a")
textFile.write(filename + " Dots number: {}".format(len(contours)) + "\n")
textFile.close()
这是我的输入图像:
以下是我的结果:
现在,这个脚本可以很好地处理这个输入,但是当我切换到其他输入时,比如:
我得到了一个非常臃肿的结果:
我只想保留以下点:
- 全面的
- 就亮度而言,这些点位于其他点的前10%
- 它们足够大(相对于图像来说,比如说去掉底部10%表面的点)
提前感谢您的帮助。去除不圆的点和小的点的一种方法是使用打开操作(您已经在使用)和您想要的最小点大小的圆形结构元素(每个比结构元素小的点都将被删除)。在下面的图像中,有一个类似于您的问题的示例,即以这种方式删除小点(源代码:)。此外,OpenCV还实现了此操作() 事实上,您已经使用了此操作,但我认为以下行中定义的结构元素似乎太小:
kernel=cv2.getStructuringElement(cv2.morp_ELLIPSE,(3,3))
此外,由于您显然使用的是不同分辨率的图像,您可以根据图像的分辨率调整结构元素的大小。去除不圆的点和小的点的一种方法是使用打开操作(您已经在使用)具有所需最小圆点大小的圆形结构元素(每个小于该结构元素的圆点都将被删除)。在以下图像中,有一个类似于您的问题的示例,其中以这种方式删除了小点(来源:)。此外,OpenCV也实现了此操作() 事实上,您已经使用了此操作,但我认为以下行中定义的结构元素似乎太小:
kernel=cv2.getStructuringElement(cv2.morp_ELLIPSE,(3,3))
此外,由于您显然使用的是具有不同分辨率的图像,因此可以根据图像的分辨率调整结构元素的大小