赞
踩
梳理下最近一个多星期的学习成果。
这次要计算的是下面这张图片,图像比较大,上传不了,先截图吧。预计颗粒数精确度为±5个,空洞率2%误差。
- # -*- coding:utf-8 -*-
- import cv2 #导入opencv模块
- import numpy as np
- import time
-
-
- def timeit(func):
- def test(*args, **kwargs):
- start = time.clock()
- res = func(*args, **kwargs)
- end = time.clock()
- print("{}函数用时为:{}分{}秒".format(func.__name__, (end - start) // 60,
- (end - start) % 60))
- return res
-
- return test
-
-
- #剪切出ROI区域
- def picture_cut(Img):
- image = cv2.imread(Img)
- image2 = image.copy()
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
- gradX = cv2.Sobel(gray, cv2.CV_32F, dx=1, dy=0, ksize=-1)
- gradY = cv2.Sobel(gray, cv2.CV_32F, dx=0, dy=1, ksize=-1)
- gradient = cv2.subtract(gradX, gradY)
- gradient = cv2.convertScaleAbs(gradient)
- blurred = cv2.blur(gradient, (9, 9))
- _, thresh = cv2.threshold(blurred, 90, 255, cv2.THRESH_BINARY)
- kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
- closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
- closed = cv2.erode(closed, None, iterations=4)
- closed = cv2.dilate(closed, None, iterations=4)
- (cnts, _) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL,
- cv2.CHAIN_APPROX_SIMPLE)
- c = sorted(cnts, key=cv2.contourArea, reverse=True)[0]
- rect = cv2.minAreaRect(c)
- box = np.int0(cv2.boxPoints(rect))
- cv2.drawContours(image, [box], -1, (0, 255, 0), 1)
- Xs = [i[0] for i in box]
- Ys = [i[1] for i in box]
- x1 = min(Xs)
- x2 = max(Xs)
- y1 = min(Ys)
- y2 = max(Ys)
- hight = y2 - y1
- width = x2 - x1
- cropImg = image2[y1:y1 + hight, x1:x1 + width]
- return cropImg
- # cv2.imwrite("before4.jpg", cropImg)
-
-
- #对ROI区域进一步进行处理
- def select_background(background, prospect):
- img = cv2.imread(background) #背景图
- oriimg = cv2.imread(prospect)
- gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
- mask = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR) #img是腐蚀膨胀完的图片
- # cv_show(oriimg, "oriimg")
- # cv_show(mask, "mask")
- ROI = cv2.bitwise_and(mask, oriimg) #oriimg是原始图片 做与运算
- return ROI
- # cv2.imwrite("test.jpg", ROI)
-
-
- #灰度加模糊处理
- def picture_filter2D(picture):
- img = cv2.imread(picture) #导入图片,图片放在程序所在目录
- img = img.copy()
- gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #转换为灰度图
- kernel = np.ones((4, 4), np.float32) / 16
- dst = cv2.filter2D(gray, -1, kernel) #2D卷积核模糊处理
- return dst
-
-
- #自适应二值化
- def picture_adaptive(dst):
- cloesd1 = cv2.adaptiveThreshold(dst, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
- cv2.THRESH_BINARY_INV, 13, 6)
- return cloesd1
-
-
- #形态学处理
- def picture_open(cloesd1):
- element = cv2.getStructuringElement(cv2.MORPH_RECT,
- (2, 4)) #形态学去噪 2,4效果最佳
- cloesd2 = cv2.morphologyEx(cloesd1, cv2.MORPH_OPEN, element) #开运算去噪
- return cloesd2
-
-
- # #画轮廓并且统计数目
- @timeit
- def contour_count(cloesd2, img):
- img = cv2.imread(img)
- contours, hierarchy = cv2.findContours(cloesd2, cv2.RETR_TREE,
- cv2.CHAIN_APPROX_SIMPLE) #轮廓检测函数
- cv2.drawContours(cloesd2, contours, -1, (0, 255, 0), 3) #绘制轮廓
- count = 0 #总数
- ares_avrg = 0 #平均
- count_small = 0 #小的颗粒数
- count_big = 0 #大的颗粒数
- big = 25
- small = 2.2
- #遍历找到的所有颗粒
- for cont in contours:
- ares = cv2.contourArea(cont) #计算包围形状的面积
- if ares > big and ares < 100: #过滤面积大于big数值的形状
- count_big += 1
- x, y, w, h = cv2.boundingRect(cont)
- cv2.rectangle(img, (x, y), (x + w, y + h), (0,0,255),
- 1) #绘制矩形 绿色
- continue
- if ares < small: #过滤面积小于small数值的形状
- count_small += 1
- continue
- if ares > 100:
- continue
- count += 1 #总体计数加1
- x, y, w, h = cv2.boundingRect(cont) #提取水平矩形坐标
- cv2.rectangle(img, (x, y), (x + w, y + h), (0,0,255), 1) #绘制矩形 红色
- print("总数为{},面积大于{}的颗粒数为{},面积小于{}的颗粒数为{},一共是{}颗!".format(
- count, big, count_big, small, count_small, count + (count_big * 2)))
- cv2.imwrite("after.jpg", img)
-
-
- #显示图片
- def cv_show(img, name):
- cv2.namedWindow(name, 1)
- cv2.imshow(name, img)
- cv2.waitKey(0)
- cv2.destroyAllWindows()
-
-
- if __name__ == "__main__":
- path = "ROI1.jpg"
- dst = picture_filter2D(path)
- cv2.imwrite("filter2D.jpg", dst)
- cloesd1 = picture_adaptive(dst)
- cv2.imwrite("thresh_binary.jpg", cloesd1)
- cloesd2 = picture_open(cloesd1)
- cv2.imwrite("morph_open.jpg", cloesd2)
- contour_count(cloesd2, path)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。