900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > python opencv利用自适应阈值分割法实现微滴图像分割并计数

python opencv利用自适应阈值分割法实现微滴图像分割并计数

时间:2023-05-30 08:46:17

相关推荐

python opencv利用自适应阈值分割法实现微滴图像分割并计数

import cv2import numpy as npblockSize = 31value = -1#count = 0 #液滴总数area = 0 #单个液滴面积min_area = 40max_area = 1500#闭运算def close(image):kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))iClose = cv2.morphologyEx(image,cv2.MORPH_CLOSE,kernel)return iClose#开运算def open(image):kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(16,16))iOpen = cv2.morphologyEx(image,cv2.MORPH_OPEN,kernel)return iOpen#查找轮廓def findConftours(srcImage,binary):contours,hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)cv2.drawContours(srcImage,contours,-1,(0,0,255),3)#遍历所有的荧光区域,计数def countAll(contours,image):global countcount = 0for i in range(np.size(contours)):area = cv2.contourArea(contours[i]) #计算闭合轮廓面积if (area < min_area) or (area > max_area):continueelse:count = count + 1(x,y),radius = cv2.minEnclosingCircle(contours[i])(x,y,radius) = np.int0((x,y,radius))cv2.circle(image,(x,y),radius,(0,0,255),2)return image,countdef cut():img = cv2.imread("E:/PythonWorkspace/yiingguang_image_process/images/1121.bmp")grayImage = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)img2 = img.copy()#ret, th1 = cv2.threshold(grayImage, 127, 255, cv2.THRESH_BINARY)# 第一个参数为原始图像矩阵,第二个参数为像素值上限,第三个是自适应方法(adaptive method):#-----cv2.ADAPTIVE_THRESH_MEAN_C:领域内均值#-----cv2.ADAPTIVE_THRESH_GAUSSIAN_C:领域内像素点加权和,权重为一个高斯窗口# 第四个值的赋值方法:只有cv2.THRESH_BINARY和cv2.THRESH_BINARY_INV# 第五个Block size:设定领域大小(一个正方形的领域)# 第六个参数C,阈值等于均值或者加权值减去这个常数(为0相当于阈值,就是求得领域内均值或者加权值)# 这种方法理论上得到的效果更好,相当于在动态自适应的调整属于自己像素点的阈值,而不是整幅图都用一个阈值#th2 = cv2.adaptiveThreshold(grayImage, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, blockSize, value)#th3 = cv2.adaptiveThreshold(grayImage, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, blockSize, value)th4 = cv2.adaptiveThreshold(grayImage, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, blockSize, value)#cv2.imshow('img', grayImage)#cv2.imshow('th1', th1)#cv2.imshow('th2', th2)#cv2.imshow('th3', th3)cv2.imshow('th4', th4)close_image = th4#去除噪声,形态学操作#闭运算iClose = close(close_image)cv2.imshow("close",iClose)#开运算后iOpen = open(iClose)cv2.imshow("close_and_open",iOpen)binary,contours,hirarchy = cv2.findContours(iOpen,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)print("所有的荧光区域:"+format(np.size(contours)))#显示轮廓res = cv2.drawContours(img,contours,-1,(0,0,255),2)#tmp = np.zeros(img.shape,np.uint8)#res = cv2.drawContours(tmp, contours, -1, (0, 0, 255), 2)cv2.imshow("cut_res",res)cv2.imwrite("adaptiveThreshold_cut_res.bmp",res)#绘制最小外接圆res,count = countAll(contours,img2)cv2.imshow("cirle_res",res)cv2.imwrite("adaptiveThreshold_cirle_res.bmp",res)print("筛选后的荧光亮点数:"+format(count))cv2.waitKey(0)cv2.destroyAllWindows()if __name__ == '__main__':cut()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。