3

我发现这段代码可以获得骨架化图像。我有一个圆形图像(https://docs.google.com/file/d/0ByS6Z5WRz-h2RXdzVGtXUTlPSGc/edit?usp=sharing)。

img = cv2.imread(nomeimg,0)
size = np.size(img)
skel = np.zeros(img.shape,np.uint8)

ret,img = cv2.threshold(img,127,255,0)
element = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
done = False

while( not done):
    eroded = cv2.erode(img,element)
    temp = cv2.dilate(eroded,element)
    temp = cv2.subtract(img,temp)
    skel = cv2.bitwise_or(skel,temp)
    img = eroded.copy()

    zeros = size - cv2.countNonZero(img)
    if zeros==size:
        done = True

print("skel")
print(skel)

cv2.imshow("skel",skel)
cv2.waitKey(0)

问题是图像结果不是“骨架”而是一组点!我的目的是在对图像进行骨架化后提取轮廓周长。如何编辑我的代码来解决它?使用 cv2.findContours 查找骨架圆是否正确?

4

2 回答 2

5

您需要反转白色和黑色,并cv2.dilate首先通过调用填充所有孔:

import numpy as np
import cv2

img = cv2.imread("e_5.jpg",0)
size = np.size(img)
skel = np.zeros(img.shape,np.uint8)

ret,img = cv2.threshold(img,127,255,0)
element = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
img = 255 - img
img = cv2.dilate(img, element, iterations=3)

done = False

while( not done):
    eroded = cv2.erode(img,element)
    temp = cv2.dilate(eroded,element)
    temp = cv2.subtract(img,temp)
    skel = cv2.bitwise_or(skel,temp)
    img = eroded.copy()

    zeros = size - cv2.countNonZero(img)
    if zeros==size:
        done = True

结果如下:

在此处输入图像描述

但是,结果并不好,因为有很多差距。以下算法更好,它使用以下函数scipy.ndimage.morphology

import scipy.ndimage.morphology as m
import numpy as np
import cv2

def skeletonize(img):
    h1 = np.array([[0, 0, 0],[0, 1, 0],[1, 1, 1]]) 
    m1 = np.array([[1, 1, 1],[0, 0, 0],[0, 0, 0]]) 
    h2 = np.array([[0, 0, 0],[1, 1, 0],[0, 1, 0]]) 
    m2 = np.array([[0, 1, 1],[0, 0, 1],[0, 0, 0]])    
    hit_list = [] 
    miss_list = []
    for k in range(4): 
        hit_list.append(np.rot90(h1, k))
        hit_list.append(np.rot90(h2, k))
        miss_list.append(np.rot90(m1, k))
        miss_list.append(np.rot90(m2, k))    
    img = img.copy()
    while True:
        last = img
        for hit, miss in zip(hit_list, miss_list): 
            hm = m.binary_hit_or_miss(img, hit, miss) 
            img = np.logical_and(img, np.logical_not(hm)) 
        if np.all(img == last):  
            break
    return img

img = cv2.imread("e_5.jpg",0)
ret,img = cv2.threshold(img,127,255,0)
element = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
img = 255 - img
img = cv2.dilate(img, element, iterations=3)

skel = skeletonize(img)
imshow(skel, cmap="gray", interpolation="nearest")

结果是:

在此处输入图像描述

于 2013-02-28T13:05:43.280 回答
0

您的骨架化算法计算白色区域的骨架:

  • Erode:将“被测像素”设置为结构元素内所有像素中的最小值,黑色 < 白色
  • Dilate:与erode相反,将“被测像素”设置为结构元素内所有像素的最大值,白色>黑色

要修复您的代码,您可以更改阈值函数的参数:

ret,img = cv2.threshold(img,240,255,1) 

参数在此处描述。

于 2013-02-28T12:55:05.427 回答