用python写二值图像骨架提取代码
时间: 2023-12-15 21:03:15 浏览: 241
骨架提取.zip_二值化_图像二值化骨架提取算法_图像骨架提取_骨架 提取_骨架化
以下是一个基于 Python 和 OpenCV 库实现的二值图像骨架提取代码:
```
import cv2
# 实现 Zhang-Suen 骨架提取算法
def thinningIteration(img, iter):
marker = cv2.bitwise_and(img, cv2.bitwise_not(cv2.erode(img, None)))
while cv2.countNonZero(marker) > 0:
temp = cv2.bitwise_and(cv2.bitwise_not(cv2.dilate(marker, None)), img)
img = cv2.bitwise_or(img, temp)
marker = cv2.bitwise_and(img, cv2.bitwise_not(cv2.erode(img, None)))
return img
# 实现 Zhang-Suen 骨架提取算法
def thinning(img):
img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1]
prev = np.zeros(img.shape, np.uint8)
diff = None
while True:
img = thinningIteration(img, 0)
img = thinningIteration(img, 1)
diff = cv2.absdiff(img, prev)
prev = img.copy()
if cv2.countNonZero(diff) == 0:
break
return img
if __name__ == '__main__':
img = cv2.imread('test.png', cv2.IMREAD_GRAYSCALE)
skeleton = thinning(img)
cv2.imshow('Skeleton', skeleton)
cv2.waitKey(0)
```
其中,`thinning()` 函数实现 Zhang-Suen 骨架提取算法,`thinningIteration()` 函数实现骨架提取的迭代过程。
调用示例:
1. 读取二值图像 `test.png`:
```
img = cv2.imread('test.png', cv2.IMREAD_GRAYSCALE)
```
2. 进行骨架提取:
```
skeleton = thinning(img)
```
3. 显示结果:
```
cv2.imshow('Skeleton', skeleton)
cv2.waitKey(0)
```
阅读全文