remove bg from pic using pthon

Solutions on MaxInterview for remove bg from pic using pthon by the best coders in the world

showing results for - "remove bg from pic using pthon"
Sky
15 Oct 2018
1import cv2
2import numpy as np
3
4#== Parameters =======================================================================
5BLUR = 21
6CANNY_THRESH_1 = 10
7CANNY_THRESH_2 = 200
8MASK_DILATE_ITER = 10
9MASK_ERODE_ITER = 10
10MASK_COLOR = (0.0,0.0,1.0) # In BGR format
11
12
13#== Processing =======================================================================
14
15#-- Read image -----------------------------------------------------------------------
16img = cv2.imread('C:/Temp/person.jpg')
17gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
18
19#-- Edge detection -------------------------------------------------------------------
20edges = cv2.Canny(gray, CANNY_THRESH_1, CANNY_THRESH_2)
21edges = cv2.dilate(edges, None)
22edges = cv2.erode(edges, None)
23
24#-- Find contours in edges, sort by area ---------------------------------------------
25contour_info = []
26_, contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
27# Previously, for a previous version of cv2, this line was: 
28#  contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
29# Thanks to notes from commenters, I've updated the code but left this note
30for c in contours:
31    contour_info.append((
32        c,
33        cv2.isContourConvex(c),
34        cv2.contourArea(c),
35    ))
36contour_info = sorted(contour_info, key=lambda c: c[2], reverse=True)
37max_contour = contour_info[0]
38
39#-- Create empty mask, draw filled polygon on it corresponding to largest contour ----
40# Mask is black, polygon is white
41mask = np.zeros(edges.shape)
42cv2.fillConvexPoly(mask, max_contour[0], (255))
43
44#-- Smooth mask, then blur it --------------------------------------------------------
45mask = cv2.dilate(mask, None, iterations=MASK_DILATE_ITER)
46mask = cv2.erode(mask, None, iterations=MASK_ERODE_ITER)
47mask = cv2.GaussianBlur(mask, (BLUR, BLUR), 0)
48mask_stack = np.dstack([mask]*3)    # Create 3-channel alpha mask
49
50#-- Blend masked img into MASK_COLOR background --------------------------------------
51mask_stack  = mask_stack.astype('float32') / 255.0          # Use float matrices, 
52img         = img.astype('float32') / 255.0                 #  for easy blending
53
54masked = (mask_stack * img) + ((1-mask_stack) * MASK_COLOR) # Blend
55masked = (masked * 255).astype('uint8')                     # Convert back to 8-bit 
56
57cv2.imshow('img', masked)                                   # Display
58cv2.waitKey()
59
60#cv2.imwrite('C:/Temp/person-masked.jpg', masked)           # Save
61