問題描述
我找到了這段代碼來獲取骨架化圖像.我有一張圓形圖片(https://docs.google.com/file/d/0ByS6Z5WRz-h2RXdzVGtXUTlPSGc/edit?usp=sharing).
I found this code to get a skeletonized image. I have a circle image (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)
問題是圖像結(jié)果不是骨架"而是一組點(diǎn)!我的目的是在對圖像進(jìn)行骨架化后提取輪廓周長.如何編輯我的代碼來解決它?使用 cv2.findContours 找骨架圈正確嗎?
The problem is that image result is not a "skeleton" but a set of points! My purpose was to extract contour perimeter after i have skeletonized the image. How can I edit my code to solve it? It is correct using cv2.findContours to find skeleton circle?
推薦答案
需要反白&黑色,然后先調(diào)用 cv2.dilate
填充所有的洞:
You need to reverse white & black, and fill all the holes by call cv2.dilate
first:
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
結(jié)果如下:
但是,結(jié)果并不好,因?yàn)橛泻芏嗖罹?以下算法更好,它使用scipy.ndimage.morphology
中的函數(shù):
But, the result is not good, because there are many gaps. The following algorithm is better, it uses functions in 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")
結(jié)果是:
這篇關(guān)于用于提取輪廓的骨架化圖像過程中的問題的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!