来吧我们画一只羊...

基本思路吧,

  1. 导入图片
  2. 得到绘图用的边界数据
  3. 调用xkcd,画出cute的sheep。

定义matplotlib的inline模式,为了能够在ipython中显示图形


In [2]:
%matplotlib inline

导入需要使用的库


In [3]:
import matplotlib.pyplot as plt
import skimage.io as io
from skimage import filter, color
import skimage.measure as ms

来吧读入我们的小绵羊


In [5]:
img = io.imread('sheep.png')
gray=color.rgb2gray(img) # 把它转换成灰度图像
plt.imshow(gray, interpolation='nearest', cmap=plt.cm.gray) #灰灰的


Out[5]:
<matplotlib.image.AxesImage at 0xe5530f0>

嗯,吧噪声抹去,只要边界,通过阈值抹去噪声


In [6]:
# otsu
thresh = filter.threshold_otsu(gray)
binary = gray <= thresh
plt.imshow(binary, interpolation='nearest', cmap=plt.cm.gray) #轮廓清晰了吧,看着也很萌哦


Out[6]:
<matplotlib.image.AxesImage at 0xe7e8890>

我知道,我很萌,但是现在还是不能很好的卖萌,因为我是一堆像素,我需要得到轮廓坐标才可以更萌


In [7]:
labels = ms.label(binary, neighbors=8)
contours = ms.find_contours(labels, 0.8) #我的边界就在这里面,就是一串一串的坐标罢了

哎,终于可以卖萌了


In [8]:
# Display the image and plot all contours found
with plt.xkcd():
    fig, ax = plt.subplots()
    ax.imshow(binary, interpolation='nearest', cmap=plt.cm.gray)
    
    for n, contour in enumerate(contours):
        ax.plot(contour[:, 1], contour[:, 0], linewidth=1)
    ax.annotate('Do you know?\n I\'m a cute sheep.', (0.2, 0.45), textcoords='axes fraction', size=20)
    
    ax.axis('image')
    ax.set_xticks([])
    ax.set_yticks([])
    plt.show()


你不用说,我知道我很萌,O(∩_∩)O~