基本信息
源码名称:分水岭算法
源码大小:1.99KB
文件格式:.py
开发语言:Python
更新时间:2021-12-14
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
分水岭算法
通过分水岭算法来完成图像分割。
import cv2 as cv import matplotlib.pyplot as plt import numpy as np def show(img): if img.ndim == 2: plt.imshow(img, cmap="gray") else: plt.imshow(cv.cvtColor(img, cv.COLOR_BGR2RGB)) def watershed(img): print(img.shape) # 直接灰度化和二值化后的图片效果不是很好,需要去噪,使用边缘保留滤波去噪声比较有效 blur = cv.pyrMeanShiftFiltering(img, 10, 100) # 灰度化 gray = cv.cvtColor(blur, cv.COLOR_BGR2GRAY) # 二值化 ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU) # 通过形态学操作,填充区域 element = cv.getStructuringElement(cv.MORPH_RECT, (3, 3)) # 进行两次开操作 morpho = cv.morphologyEx(binary, cv.MORPH_OPEN, element, iterations=2) # 进行膨胀操作 img_bg = cv.dilate(morpho, element, iterations=3) # 对两次开操作图像进行距离变换 distance = cv.distanceTransform(morpho, cv.DIST_L2, 3) # 最亮的地方为marker,通过阈值来获取 ret, bright = cv.threshold(distance, distance.max()*0.6, 255, cv.THRESH_BINARY) # float类型转换成8位数的 img_fg = np.uint8(bright) unknown = cv.subtract(img_bg, img_fg) # marker,连通区域 ret, markers = cv.connectedComponents(img_fg) # markers可以完成分水岭变换 markers = markers 1 markers[unknown == 255] = 0 markers = cv.watershed(img, markers=markers) # 红色标记 img[markers == -1] = [0, 0, 255] return img image = cv.imread("D:/img/coins.jpg") plt.rcParams['font.sans-serif'] = ['SimHei'] plt.figure(figsize=(6, 6)) plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.2, hspace=0) plt.subplot(1, 2, 1) show(image) plt.title("原图像") plt.axis("off") plt.subplot(1, 2, 2) binary = watershed(image) show(binary) plt.title("分水岭法后图像") plt.axis("off") plt.show() cv.waitKey(0) cv.destroyAllWindows()