Created
          September 11, 2019 15:34 
        
      - 
      
- 
        Save shubhamwagh/b8148e65a8850a974efd37107ce3f2ec to your computer and use it in GitHub Desktop. 
    Smooth contours in Opencv 
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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) | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment