Make Edges of the Image smooth Ask

asked 2020-08-22 11:03:57 -0600

usamajamil32 gravatar image

updated 2020-08-22 13:10:11 -0600

I am currently working a simple project
It is removing the Background of any image and converting it into a Sticker but it is not Giving me Smoother

import cv2
import numpy as np
from PIL import Image, ImageFilter
from google.colab.patches import cv2_imshow
from matplotlib import pyplot as pl
#img = cv2.imread("/content/police-car-icon-cartoon-style-vector-16884775.jpg")
remove_background("/content/WhatsApp Image 2020-08-17 at 1.08.33 AM (2).jpeg")




def remove_background(img1):

#== Parameters =======================================================================

BLUR = 5
CANNY_THRESH_1 = 10
CANNY_THRESH_2 = 100
MASK_DILATE_ITER = 10
MASK_ERODE_ITER = (1,1)
MASK_COLOR = (220,220,220) # In BGR format

#== Processing =======================================================================

#-- Read image -----------------------------------------------------------------------
img = cv2.imread(img1)
#img = cv2.resize(img, (600,600))
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

#-- Edge detection -------------------------------------------------------------------
edges = cv2.Canny(gray, CANNY_THRESH_1, CANNY_THRESH_2)
edges = cv2.dilate(edges, None)
##edges = cv2.erode(edges, None)

#-- Find contours in edges, sort by area ---------------------------------------------
contour_info = []
contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)

for c in contours:
    contour_info.append((
        c,
        cv2.isContourConvex(c),
        cv2.contourArea(c),
    ))
contour_info = sorted(contour_info, key=lambda c: c[2], reverse=True)


#-- Create empty mask, draw filled polygon on it corresponding to largest contour ----
# Mask is black, polygon is white
mask = np.zeros(edges.shape)
for c in contour_info:
    cv2.fillConvexPoly(mask, c[0], (255))
# cv2.fillConvexPoly(mask, max_contour[0], (255))

#-- Smooth mask, then blur it --------------------------------------------------------
mask = cv2.dilate(mask, None, iterations=MASK_DILATE_ITER)
mask_stack = np.dstack([mask]*3)    # Create 3-channel alpha mask

mask_u8 = np.array(mask,np.uint8)

back = np.zeros(mask.shape,np.uint8)
back[mask_u8 == 0] = 255

border = cv2.Canny(mask_u8, CANNY_THRESH_1, CANNY_THRESH_2)
border = cv2.dilate(border, None, iterations=3)


masked = mask_stack * img  # Blend
masked = (masked * 255).astype('uint8')

#     background Colors (blue,green,red)
masked[:,:,0][back == 255] = 190
masked[:,:,1][back == 255] = 190
masked[:,:,2][back == 255] = 190





cv2.imwrite('img.png', masked)

cv2_imshow(  masked)

cv2.waitKey(0)
cv2.destroyAllWindows()

Working on this Image

This is the Output Image

But I want this image to be little smoother like this

edit retag flag offensive close merge delete