1、读取图片 2、转为灰度图片 3、滤波降噪 4、二值化 5、形态学处理,开闭运算,腐蚀填充 6、画轮廓,外接矩形,计算面积等 基于4.0.9.80 opencv版本
import cv2 as cv import numpy as np def show(img, title): cv.imshow(title, img) cv.waitKey() cv.destroyAllWindows() image = cv.imread('./image_cn_web/luomao.png') image_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY) # 灰度图 image_blur = cv.GaussianBlur(image_gray, (25, 25), 0, 0) # 过滤降噪 # show(image_blur, '过滤降噪') # 二值化 img_bin = cv.adaptiveThreshold(image_blur, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY_INV, blockSize=35, C=2) show(img_bin, '二值化') # 形态学处理 kernel = np.ones((3, 3), np.uint8) img_bin_open = cv.morphologyEx(img_bin, cv.MORPH_OPEN, kernel) # 开运算 show(img_bin_open, '开运算') kernel = np.ones((25, 25), np.uint8) img_bin_close = cv.morphologyEx(img_bin_open, cv.MORPH_CLOSE, kernel) # 闭运算 show(img_bin_close, '闭运算') kernel = np.ones((7, 7), np.uint8) image_bin_open = cv.morphologyEx(img_bin_close, cv.MORPH_OPEN, kernel) # 开运算 show(img_bin_open, '开运算') kernel = np.ones((25, 25), np.uint8) image_bin_close = cv.morphologyEx(image_bin_open, cv.MORPH_CLOSE, kernel) # 闭运算 show(img_bin_close, '闭运算') cnts, hierarchy = cv.findContours(image_bin_close, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) img2 = image.copy() img_withcontours = cv.drawContours(img2, cnts, -1, (0, 0, 255), 3) # cv.imshow('result', img_withcontours) # cv.waitKey() # cv.destroyAllWindows()
标签:bin,kernel,img,image,opencv,np,轮廓,cv From: https://www.cnblogs.com/luckygxf/p/18107399