From dcbea756775f9e531861bd0df4a49480012277b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20Sch=C3=B6nberger?= Date: Mon, 13 Aug 2012 22:21:40 +0200 Subject: [PATCH] improved polygon approximation example script made existing example parameters more readable and add another example with a more complex shape based on a subdivision algorithm. --- doc/examples/plot_approximate_polygon.py | 60 +++++++++++++++++++++--- 1 file changed, 53 insertions(+), 7 deletions(-) diff --git a/doc/examples/plot_approximate_polygon.py b/doc/examples/plot_approximate_polygon.py index cec98492..ec7e4f4d 100644 --- a/doc/examples/plot_approximate_polygon.py +++ b/doc/examples/plot_approximate_polygon.py @@ -9,6 +9,7 @@ algorithm. import numpy as np import matplotlib.pyplot as plt +from scipy import signal from skimage.draw import ellipse from skimage.measure import find_contours, approximate_polygon @@ -20,15 +21,60 @@ img[rr, cc] = 1 rr, cc = ellipse(600, 600, 150, 90, img.shape) img[rr, cc] = 1 +hand = np.array([[1.64516129, 1.16145833], + [1.64516129, 1.59375 ], + [1.35080645, 1.921875 ], + [1.375 , 2.18229167], + [1.68548387, 1.9375 ], + [1.60887097, 2.55208333], + [1.68548387, 2.69791667], + [1.76209677, 2.56770833], + [1.83064516, 1.97395833], + [1.89516129, 2.75 ], + [1.9516129 , 2.84895833], + [2.01209677, 2.76041667], + [1.99193548, 1.99479167], + [2.11290323, 2.63020833], + [2.2016129 , 2.734375 ], + [2.25403226, 2.60416667], + [2.14919355, 1.953125 ], + [2.30645161, 2.36979167], + [2.39112903, 2.36979167], + [2.41532258, 2.1875 ], + [2.1733871 , 1.703125 ], + [2.07782258, 1.16666667]]) + + +def doo_sabin_subdivision(points): + new_points = np.zeros((2 * (len(points) - 1), 2)) + new_points[::2] = 3 / 4. * points[:-1] + 1 / 4. * points[1:] + new_points[1::2] = 1 / 4. * points[:-1] + 3 / 4. * points[1:] + return new_points + +new_hand = hand.copy() +for _ in range(5): + new_hand = doo_sabin_subdivision(new_hand) + +appr_hand = approximate_polygon(new_hand, tolerance=0.02) + +print "Number of coordinates:", len(hand), len(new_hand), len(appr_hand) + +fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(9, 4)) + +ax1.plot(hand[:, 0], hand[:, 1]) +ax1.plot(new_hand[:, 0], new_hand[:, 1]) +ax1.plot(appr_hand[:, 0], appr_hand[:, 1]) + plt.gray() -plt.imshow(img) +ax2.imshow(img) for contour in find_contours(img, 0): - coords = approximate_polygon(contour, 4) - plt.plot(coords[:, 1], coords[:, 0], '-r', linewidth=2) - coords = approximate_polygon(contour, 40) - plt.plot(coords[:, 1], coords[:, 0], '-g', linewidth=2) + coords = approximate_polygon(contour, tolerance=2.5) + ax2.plot(coords[:, 1], coords[:, 0], '-r', linewidth=2) + coords2 = approximate_polygon(contour, tolerance=39.5) + ax2.plot(coords2[:, 1], coords2[:, 0], '-g', linewidth=2) + print "Number of coordinates:", len(contour), len(coords), len(coords2) + +ax2.axis((0, 800, 0, 800)) -plt.axis((0, 800, 0, 800)) -plt.axis('off') plt.show()