Skip to content

Instantly share code, notes, and snippets.

@shubhamwagh
Created September 11, 2019 15:34
Show Gist options
  • Save shubhamwagh/b8148e65a8850a974efd37107ce3f2ec to your computer and use it in GitHub Desktop.
Save shubhamwagh/b8148e65a8850a974efd37107ce3f2ec to your computer and use it in GitHub Desktop.

Revisions

  1. shubhamwagh created this gist Sep 11, 2019.
    1 change: 1 addition & 0 deletions Link.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    [Link](https://agniva.me/scipy/2016/10/25/contour-smoothing.html)
    22 changes: 22 additions & 0 deletions contour_smooth.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    import numpy
    import cv2
    from scipy.interpolate import splprep, splev

    smoothened = []
    for contour in contours:
    x,y = contour.T
    # Convert from numpy arrays to normal arrays
    x = x.tolist()[0]
    y = y.tolist()[0]
    # https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.splprep.html
    tck, u = splprep([x,y], u=None, s=1.0, per=1)
    # https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.linspace.html
    u_new = numpy.linspace(u.min(), u.max(), 25)
    # https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.splev.html
    x_new, y_new = splev(u_new, tck, der=0)
    # Convert it back to numpy format for opencv to be able to display it
    res_array = [[[int(i[0]), int(i[1])]] for i in zip(x_new,y_new)]
    smoothened.append(numpy.asarray(res_array, dtype=numpy.int32))

    # Overlay the smoothed contours on the original image
    cv2.drawContours(original_img, smoothened, -1, (255,255,255), 2)