python
import cv2
import numpy as np
def zhang_suen_thinning(src_img):
# 将原始图像转换为二值图像
_, binary_img = cv2.threshold(src_img, 127, 255, cv2.THRESH_BINARY)
# 创建标记图像并初始化为全零
mark_img = np.zeros_like(binary_img)
# 迭代处理标记图像的像素,根据Zhang-Suen算法对像素值进行修改
has_change = True
while has_change:
has_change = False
for y in range(1, binary_img.shape[0]-1):
for x in range(1, binary_img.shape[1]-1):
current_pixel = binary_img[y, x]
if current_pixel == 0:
continue
nb_pixels = [binary_img[y-1, x], binary_img[y-1, x+1], binary_img[y, x+1], binary_img[y+1, x+1],
binary_img[y+1, x], binary_img[y+1, x-1], binary_img[y, x-1], binary_img[y-1, x-1]]
p2p3p4p5_transition = 0
for i in range(0, 8):
if nb_pixels[i] == 0 and nb_pixels[(i+1) % 8] == 255:
p2p3p4p5_transition += 1
p1_transition = 0
if nb_pixels[0] == 0 and nb_pixels[1] == 255:
p1_transition = 1
p1_to_p8_transition = np.sum(np.array(nb_pixels) == 255) - np.sum(np.array(nb_pixels[0::2]) == 255)
if (p2p3p4p5_transition == 1 and p1_transition == 1 and p1_to_p8_transition >= 2 and p1_to_p8_transition <= 6 and
nb_pixels[0] * nb_pixels[2] * nb_pixels[4] == 0 and nb_pixels[2] * nb_pixels[4] * nb_pixels[6] == 0):
mark_img[y, x] = 1
has_change = True
# 执行第二次迭代,将满足条件的像素值设为0
if not has_change:
for y in range(1, binary_img.shape[0]-1):
for x in range(1, binary_img.shape[1]-1):
if mark_img[y, x] ==