1 Star 0 Fork 0

杨雪锋/opencv-python-5

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
c8-17.py 1.64 KB
一键复制 编辑 原始数据 按行查看 历史
杨雪锋 提交于 2023-04-14 21:51 +08:00 . update ch8
import cv2 as cv
import numpy as np
img = cv.imread('coins.jpg')
img2 = img.copy()
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(gray,0,255,cv.THRESH_BINARY_INV+cv.THRESH_OTSU)
# 去噪,开运算
kernel = np.ones((3,3),np.uint8)
opening = cv.morphologyEx(thresh,cv.MORPH_OPEN,kernel, iterations = 2)
# 确定背景区域
sure_bg = cv.dilate(opening,kernel,iterations=3)
# 获取前景区域
dist_transform = cv.distanceTransform(opening,cv.DIST_L2,5)
ret, sure_fg = cv.threshold(dist_transform,0.7*dist_transform.max(),255,0)
# 查找未知区域
sure_fg = np.uint8(sure_fg)
unknown = cv.subtract(sure_bg,sure_fg)
# 对连通区域标号,0到N-1
ret, markers = cv.connectedComponents(sure_fg)
# OpenCV 分水岭算法对物体做的标注必须都大于1,所以为所有标签添加一个,以确保背景不是0,而是1。
markers = markers+1
# 将未知区域标记为0。
markers[unknown==255] = 0
# 进行分水岭算法,运算后,所有轮廓的像素点被标注为-1
markers = cv.watershed(img,markers)
# 标注为-1的像素点标红
img[markers == -1] = [0,0,255]
# 显示结果
cv.imshow('fig8-15a.png',img2)
cv.imshow('fig8-15b.png',cv.bitwise_not(opening))
cv.imshow('fig8-15c.png',cv.bitwise_not(sure_bg))
cv.imshow('fig8-15d.png',cv.bitwise_not(sure_fg))
cv.imshow('fig8-15e.png',cv.bitwise_not(unknown))
cv.imshow('fig8-15f.png',img)
cv.imwrite('fig8-15a.png',img2)
cv.imwrite('fig8-15b.png',cv.bitwise_not(opening))
cv.imwrite('fig8-15c.png',cv.bitwise_not(sure_bg))
cv.imwrite('fig8-15d.png',cv.bitwise_not(sure_fg))
cv.imwrite('fig8-15e.png',cv.bitwise_not(unknown))
cv.imwrite('fig8-15f.png',img)
cv.waitKey(0)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/hopeasy/opencv-python-5.git
git@gitee.com:hopeasy/opencv-python-5.git
hopeasy
opencv-python-5
opencv-python-5
master

搜索帮助