Python cv2.GC_INIT_WITH_RECT Examples
The following are 2
code examples of cv2.GC_INIT_WITH_RECT().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
cv2
, or try the search function
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: image_segmentation.py From OpenCV-3-x-with-Python-By-Example with MIT License | 7 votes |
def run_grabcut(img_orig, rect_final): # Initialize the mask mask = np.zeros(img_orig.shape[:2],np.uint8) # Extract the rectangle and set the region of # interest in the above mask x,y,w,h = rect_final mask[y:y+h, x:x+w] = 1 # Initialize background and foreground models bgdModel = np.zeros((1,65), np.float64) fgdModel = np.zeros((1,65), np.float64) # Run Grabcut algorithm cv2.grabCut(img_orig, mask, rect_final, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT) # Extract new mask mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8') # Apply the above mask to the image img_orig = img_orig*mask2[:,:,np.newaxis] # Display the image cv2.imshow('Output', img_orig)
Example #2
Source File: grab_cut.py From Interactive-image-segmentation-opencv-qt with MIT License | 4 votes |
def image_matting(self, image_file, shape, iteration=10): points = shape['points'] xmin, ymin, xmax, ymax = Grab_cut.convertPoints2BndBox(points) self.width = xmax - xmin self.height = ymax - ymin src_img = cv2.imread(image_file) mask = np.zeros(src_img.shape[:2], np.uint8) bgdModel = np.zeros((1, 65), np.float64) fgdModel = np.zeros((1, 65), np.float64) rect = (xmin, ymin, self.width, self.height) # Grabcut cv2.grabCut(src_img, mask, rect, bgdModel, fgdModel, iteration, cv2.GC_INIT_WITH_RECT) r_channel, g_channel, b_channel = cv2.split(src_img) a_channel = np.where((mask == 2) | (mask == 0), 0, 255).astype('uint8') # crop image space for row in range(ymin, ymax): if sum(r_channel[row, xmin:xmax + 1]) > 0: out_ymin = row break for row in range(ymin, ymax)[::-1]: if sum(r_channel[row, xmin:xmax + 1]) > 0: out_ymax = row + 1 break for col in range(xmin, xmax): if sum(a_channel[ymin:ymax + 1, col]) > 0: out_xmin = col break for col in range(xmin, xmax)[::-1]: if sum(a_channel[ymin:ymax + 1, col]) > 0: out_xmax = col + 1 break # output image img_RGBA = cv2.merge((r_channel[out_ymin:out_ymax, out_xmin:out_xmax], g_channel[out_ymin:out_ymax, out_xmin:out_xmax], b_channel[out_ymin:out_ymax, out_xmin:out_xmax], a_channel[out_ymin:out_ymax, out_xmin:out_xmax])) return img_RGBA