opencv 画轮廓

复制代码
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()
复制代码

 

posted on   luckygxf  阅读(18)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示