Python cv2.fillPoly() Examples

The following are 30 code examples of cv2.fillPoly(). 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 .
Example #1
Source File: tgc_visualizer.py    From TGC-Designer-Tools with Apache License 2.0 8 votes vote down vote up
def drawSplinesOnImage(splines, color, im, pc, image_scale):
    for s in splines:
        # Get the shape of this spline and draw it on the image
        nds = []
        for wp in s["waypoints"]:
            nds.append(pc.tgcToCV2(wp["waypoint"]["x"], wp["waypoint"]["y"], image_scale))

        # Don't try to draw malformed splines
        if len(nds) == 0:
            continue

        # Uses points and not image pixels, so flip the x and y
        nds = np.array(nds)
        nds[:,[0, 1]] = nds[:,[1, 0]]
        nds = np.int32([nds]) # Bug with fillPoly, needs explict cast to 32bit

        thickness = int(s["width"])
        if(thickness < image_scale):
            thickness = int(image_scale)

        if s["isFilled"]:
            cv2.fillPoly(im, nds, color, lineType=cv2.LINE_AA)
        else:
            cv2.polylines(im, nds, s["isClosed"], color, thickness, lineType=cv2.LINE_AA) 
Example #2
Source File: RegionOfInterest.py    From DoNotSnap with GNU General Public License v3.0 7 votes vote down vote up
def findEllipses(edges):
    contours, _ = cv2.findContours(edges.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    ellipseMask = np.zeros(edges.shape, dtype=np.uint8)
    contourMask = np.zeros(edges.shape, dtype=np.uint8)

    pi_4 = np.pi * 4

    for i, contour in enumerate(contours):
        if len(contour) < 5:
            continue

        area = cv2.contourArea(contour)
        if area <= 100:  # skip ellipses smaller then 10x10
            continue

        arclen = cv2.arcLength(contour, True)
        circularity = (pi_4 * area) / (arclen * arclen)
        ellipse = cv2.fitEllipse(contour)
        poly = cv2.ellipse2Poly((int(ellipse[0][0]), int(ellipse[0][1])), (int(ellipse[1][0] / 2), int(ellipse[1][1] / 2)), int(ellipse[2]), 0, 360, 5)

        # if contour is circular enough
        if circularity > 0.6:
            cv2.fillPoly(ellipseMask, [poly], 255)
            continue

        # if contour has enough similarity to an ellipse
        similarity = cv2.matchShapes(poly.reshape((poly.shape[0], 1, poly.shape[1])), contour, cv2.cv.CV_CONTOURS_MATCH_I2, 0)
        if similarity <= 0.2:
            cv2.fillPoly(contourMask, [poly], 255)

    return ellipseMask, contourMask 
Example #3
Source File: mesh.py    From plumo with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def fill_convex (image):
    H, W = image.shape
    padded = np.zeros((H+20, W+20), dtype=np.uint8)
    padded[10:(10+H),10:(10+W)] = image

    contours = measure.find_contours(padded, 0.5)
    if len(contours) == 0:
        return image
    if len(contours) == 1:
        contour = contours[0]
    else:
        contour = np.vstack(contours)
    cc = np.zeros_like(contour, dtype=np.int32)
    cc[:,0] = contour[:, 1]
    cc[:,1] = contour[:, 0]
    hull = cv2.convexHull(cc)
    contour = hull.reshape((1, -1, 2)) 
    cv2.fillPoly(padded, contour, 1)
    return padded[10:(10+H),10:(10+W)] 
Example #4
Source File: OSMTGC.py    From TGC-Designer-Tools with Apache License 2.0 6 votes vote down vote up
def drawWayOnImage(way, color, im, pc, image_scale, thickness=-1, x_offset=0.0, y_offset=0.0):
    # Get the shape of this way and draw it as a poly
    nds = []
    for node in way.get_nodes(resolve_missing=True): # Allow automatically resolving missing nodes, but this is VERY slow with the API requests, try to request them above instead
        nds.append(pc.latlonToCV2(node.lat, node.lon, image_scale, x_offset, y_offset))
    # Uses points and not image pixels, so flip the x and y
    nds = np.array(nds)
    nds[:,[0, 1]] = nds[:,[1, 0]]
    nds = np.int32([nds]) # Bug with fillPoly, needs explict cast to 32bit
    cv2.fillPoly(im, nds, color) 

    # Add option to draw shape again, but with thick line
    # Use this to automatically expand some shapes, for example water
    # For better masking
    if thickness > 0:
        # Need to draw again since fillPoly has no line thickness options that I've found
        cv2.polylines(im, nds, True, color, thickness, lineType=cv2.LINE_AA) 
Example #5
Source File: util.py    From SpaceNet_Off_Nadir_Solutions with Apache License 2.0 6 votes vote down vote up
def mask_for_polygons(polygons, im_size=(900, 900)):
    # __author__ = Konstantin Lopuhin
    # https://www.kaggle.com/lopuhin/dstl-satellite-imagery-feature-detection/full-pipeline-demo-poly-pixels-ml-poly

    int_coords = lambda x: np.array(x).round().astype(np.int32)
    all_mask = np.zeros(im_size, np.uint8)
    for i, poly in enumerate(polygons):
        exteriors = []
        interiors = []
        if poly.has_z:
            exteriors.append(int_coords([(item[0:2]) for item in poly.exterior.coords]))
            for pi in poly.interiors:
                pi = [(item[0:2]) for item in pi.coords]
                interiors.append(int_coords(pi))
        else:
            exteriors.append(int_coords(poly.exterior.coords))
            for pi in poly.interiors:
                interiors.append(int_coords(pi.coords))
        cv2.fillPoly(all_mask, exteriors, i + 1)
        cv2.fillPoly(all_mask, interiors, 0)
    return all_mask 
Example #6
Source File: shapes.py    From PanopticSegmentation with MIT License 6 votes vote down vote up
def draw_shape(self, image, shape, dims, color):
        """Draws a shape from the given specs."""
        # Get the center x, y and the size s
        x, y, s = dims
        if shape == 'square':
            image = cv2.rectangle(image, (x - s, y - s),
                                  (x + s, y + s), color, -1)
        elif shape == "circle":
            image = cv2.circle(image, (x, y), s, color, -1)
        elif shape == "triangle":
            points = np.array([[(x, y - s),
                                (x - s / math.sin(math.radians(60)), y + s),
                                (x + s / math.sin(math.radians(60)), y + s),
                                ]], dtype=np.int32)
            image = cv2.fillPoly(image, points, color)
        return image 
Example #7
Source File: part-6-lane-finder.py    From pygta5 with GNU General Public License v3.0 6 votes vote down vote up
def roi(img, vertices):
    
    #blank mask:
    mask = np.zeros_like(img)   
    
    #filling pixels inside the polygon defined by "vertices" with the fill color    
    cv2.fillPoly(mask, vertices, 255)
    
    #returning the image only where mask pixels are nonzero
    masked = cv2.bitwise_and(img, mask)
    return masked 
Example #8
Source File: image_process.py    From Advanced_Lane_Lines with MIT License 6 votes vote down vote up
def draw_lane_fit(undist, warped ,Minv, left_fitx, right_fitx, ploty):
	# Drawing
	# Create an image to draw the lines on
	warp_zero = np.zeros_like(warped).astype(np.uint8)
	color_warp = np.dstack((warp_zero, warp_zero, warp_zero))

	# Recast the x and y points into usable format for cv2.fillPoly()
	pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])
	pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])
	pts = np.hstack((pts_left, pts_right))

	# Draw the lane onto the warped blank image
	cv2.fillPoly(color_warp, np.int_([pts]), (0,255,0))

	# Warp the blank back to original image space using inverse perspective matrix(Minv)
	newwarp = cv2.warpPerspective(color_warp, Minv, (undist.shape[1], undist.shape[0]))
	# Combine the result with the original image
	result = cv2.addWeighted(undist, 1, newwarp, 0.3, 0)

	return result 
Example #9
Source File: apply_makeup.py    From visage with MIT License 6 votes vote down vote up
def __fill_lip_solid(self, outer, inner):
        """ Fills solid colour inside two outlines. """
        inner[0].reverse()
        inner[1].reverse()
        outer_curve = zip(outer[0], outer[1])
        inner_curve = zip(inner[0], inner[1])
        points = []
        for point in outer_curve:
            points.append(np.array(point, dtype=np.int32))
        for point in inner_curve:
            points.append(np.array(point, dtype=np.int32))
        points = np.array(points, dtype=np.int32)
        self.red_l = int(self.red_l)
        self.green_l = int(self.green_l)
        self.blue_l = int(self.blue_l)
        cv2.fillPoly(self.image, [points], (self.red_l, self.green_l, self.blue_l)) 
Example #10
Source File: shapes.py    From Mask-RCNN-Pedestrian-Detection with MIT License 6 votes vote down vote up
def draw_shape(self, image, shape, dims, color):
        """Draws a shape from the given specs."""
        # Get the center x, y and the size s
        x, y, s = dims
        if shape == 'square':
            image = cv2.rectangle(image, (x - s, y - s),
                                  (x + s, y + s), color, -1)
        elif shape == "circle":
            image = cv2.circle(image, (x, y), s, color, -1)
        elif shape == "triangle":
            points = np.array([[(x, y - s),
                                (x - s / math.sin(math.radians(60)), y + s),
                                (x + s / math.sin(math.radians(60)), y + s),
                                ]], dtype=np.int32)
            image = cv2.fillPoly(image, points, color)
        return image 
Example #11
Source File: mask.py    From lighttrack with MIT License 6 votes vote down vote up
def showMask(img_obj):
    img = cv2.imread(img_obj['fpath'])
    img_ori = img.copy()
    gtmasks = img_obj['gtmasks']
    n = len(gtmasks)
    print(img.shape)
    for i, mobj in enumerate(gtmasks):
        if not (type(mobj['mask']) is list):
            print("Pass a RLE mask")
            continue
        else:
            pts = np.round(np.asarray(mobj['mask'][0]))
            pts = pts.reshape(pts.shape[0] // 2, 2)
            pts = np.int32(pts)
            color = np.uint8(np.random.rand(3) * 255).tolist()
            cv2.fillPoly(img, [pts], color)
    cv2.addWeighted(img, 0.5, img_ori, 0.5, 0, img)
    cv2.imshow("Mask", img)
    cv2.waitKey(0) 
Example #12
Source File: annotation.py    From imantics with MIT License 6 votes vote down vote up
def mask(self, width=None, height=None):
        """
        Returns or generates :class:`Mask` representation of polygons.

        :returns: Mask representation
        :rtype: :class:`Mask`
        """
        if not self._c_mask:

            size = height, width if height and width else self.bbox().max_point
            # Generate mask from polygons

            mask = np.zeros(size)
            mask = cv2.fillPoly(mask, self.points, 1)
            
            self._c_mask = Mask(mask)
            self._c_mask._c_polygons = self
        
        return self._c_mask 
Example #13
Source File: line_utils.py    From VerifAI with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def draw(self, mask, color=(255, 0, 0), line_width=50, average=False):
        """
        Draw the line on a color mask image.
        """
        h, w, c = mask.shape

        plot_y = np.linspace(0, h - 1, h)
        coeffs = self.average_fit if average else self.last_fit_pixel

        line_center = coeffs[0] * plot_y ** 2 + coeffs[1] * plot_y + coeffs[2]
        line_left_side = line_center - line_width // 2
        line_right_side = line_center + line_width // 2

        # Some magic here to recast the x and y points into usable format for cv2.fillPoly()
        pts_left = np.array(list(zip(line_left_side, plot_y)))
        pts_right = np.array(np.flipud(list(zip(line_right_side, plot_y))))
        pts = np.vstack([pts_left, pts_right])

        # Draw the lane onto the warped blank image
        return cv2.fillPoly(mask, [np.int32(pts)], color) 
Example #14
Source File: detector_utils.py    From HandGesturesDroneController with Apache License 2.0 6 votes vote down vote up
def draw_right_arrow(img,shift_arrow):
    wheel_color = (200,200,200)
    shift_from_center = 55
    overlay = img.copy()
    # (2) draw shapes:
    # (3) blend with the original:
    opacity = 0.7
    
    cv2.line(overlay,(int((img.shape[1]/2)-shift_from_center+shift_arrow*5),int(img.shape[0]/2)),(int(((img.shape[1]/2))+shift_from_center+shift_arrow*5),int(img.shape[0]/2)),wheel_color , 15)
    pts = np.array([[int(((img.shape[1]/2))+shift_from_center+shift_arrow*5)+25,int(img.shape[0]/2)]
    ,[int(((img.shape[1]/2))+shift_from_center+shift_arrow*5),int(img.shape[0]/2)-25],
    [int(((img.shape[1]/2))+shift_from_center+shift_arrow*5),int(img.shape[0]/2)+25]],
    np.int32)
    pts = pts.reshape((-1,1,2))
    # cv2.fillPoly(img,[pts],wheel_color,-1)
    cv2.fillPoly(overlay, [pts], wheel_color, 8)
    cv2.addWeighted(overlay, opacity, img, 1 - opacity, 0, img)

    return img 
Example #15
Source File: detector_utils.py    From HandGesturesDroneController with Apache License 2.0 6 votes vote down vote up
def draw_left_arrow(img,shift_arrow):
    wheel_color = (200,200,200)
    shift_from_center = 55
    overlay = img.copy()
    # (2) draw shapes:
    # (3) blend with the original:
    opacity = 0.7
    
    cv2.line(overlay,(int((img.shape[1]/2)-shift_from_center-shift_arrow*5),int(img.shape[0]/2)),(int(((img.shape[1]/2))+shift_from_center-shift_arrow*5),int(img.shape[0]/2)),wheel_color , 15)
    pts = np.array([[int(((img.shape[1]/2))-shift_from_center-shift_arrow*5)-25,int(img.shape[0]/2)]
    ,[int(((img.shape[1]/2))-shift_from_center-shift_arrow*5),int(img.shape[0]/2)-25],
    [int(((img.shape[1]/2))-shift_from_center-shift_arrow*5),int(img.shape[0]/2)+25]],
    np.int32)
    pts = pts.reshape((-1,1,2))
    # cv2.fillPoly(img,[pts],wheel_color,-1)
    cv2.fillPoly(overlay, [pts], wheel_color, 8)
    cv2.addWeighted(overlay, opacity, img, 1 - opacity, 0, img)

    return img 
Example #16
Source File: detector_utils.py    From HandGesturesDroneController with Apache License 2.0 6 votes vote down vote up
def draw_up_arrow(img,shift_arrow):
    wheel_color = (200,200,200)
    shift_from_center = 55
    overlay = img.copy()
    # (2) draw shapes:
    # (3) blend with the original:
    opacity = 0.7
    
    cv2.line(overlay,(int((img.shape[1]/2)),int(img.shape[0]/2)-shift_from_center-shift_arrow*5),(int(((img.shape[1]/2))),int(img.shape[0]/2)+shift_from_center-shift_arrow*5),wheel_color , 15)
    pts = np.array([[int((img.shape[1]/2)),int((img.shape[0]/2-shift_from_center-shift_arrow*5))-25]
    ,[int((img.shape[1]/2))-25,int((img.shape[0]/2)-shift_from_center-shift_arrow*5)],
    [int((img.shape[1]/2))+25,int((img.shape[0]/2-shift_from_center-shift_arrow*5))]],
    np.int32)
    pts = pts.reshape((-1,1,2))
    # cv2.fillPoly(img,[pts],wheel_color,-1)
    cv2.fillPoly(overlay, [pts], wheel_color, 8)
    cv2.addWeighted(overlay, opacity, img, 1 - opacity, 0, img)

    return img 
Example #17
Source File: detector_utils.py    From HandGesturesDroneController with Apache License 2.0 6 votes vote down vote up
def draw_down_arrow(img,shift_arrow):
    wheel_color = (200,200,200)
    shift_from_center = 55
    overlay = img.copy()
    # (2) draw shapes:
    # (3) blend with the original:
    opacity = 0.7
    
    cv2.line(overlay,(int((img.shape[1]/2)),int(img.shape[0]/2)-shift_from_center+shift_arrow*5),(int(((img.shape[1]/2))),int(img.shape[0]/2)+shift_from_center+shift_arrow*5),wheel_color , 15)
    pts = np.array([[int((img.shape[1]/2)),int((img.shape[0]/2+shift_from_center+shift_arrow*5))+25]
    ,[int((img.shape[1]/2))-25,int((img.shape[0]/2)+shift_from_center+shift_arrow*5)],
    [int((img.shape[1]/2))+25,int((img.shape[0]/2+shift_from_center+shift_arrow*5))]],
    np.int32)
    pts = pts.reshape((-1,1,2))
    # cv2.fillPoly(img,[pts],wheel_color,-1)
    cv2.fillPoly(overlay, [pts], wheel_color, 8)
    cv2.addWeighted(overlay, opacity, img, 1 - opacity, 0, img)

    return img 
Example #18
Source File: shapes.py    From DeepTL-Lane-Change-Classification with MIT License 6 votes vote down vote up
def draw_shape(self, image, shape, dims, color):
        """Draws a shape from the given specs."""
        # Get the center x, y and the size s
        x, y, s = dims
        if shape == 'square':
            image = cv2.rectangle(image, (x - s, y - s),
                                  (x + s, y + s), color, -1)
        elif shape == "circle":
            image = cv2.circle(image, (x, y), s, color, -1)
        elif shape == "triangle":
            points = np.array([[(x, y - s),
                                (x - s / math.sin(math.radians(60)), y + s),
                                (x + s / math.sin(math.radians(60)), y + s),
                                ]], dtype=np.int32)
            image = cv2.fillPoly(image, points, color)
        return image 
Example #19
Source File: lane.py    From vehicle-detection with GNU General Public License v3.0 6 votes vote down vote up
def compute_car_offcenter(ploty, left_fitx, right_fitx, undist):

    # Create an image to draw the lines on
    height = undist.shape[0]
    width = undist.shape[1]

    # Recast the x and y points into usable format for cv2.fillPoly()
    pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])
    pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])
    pts = np.hstack((pts_left, pts_right))

    bottom_l = left_fitx[height-1]
    bottom_r = right_fitx[0]

    offcenter = off_center(bottom_l, width/2.0, bottom_r)

    return offcenter, pts 
Example #20
Source File: mesh.py    From plumo with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def fill_convex (image):
    H, W = image.shape
    padded = np.zeros((H+20, W+20), dtype=np.uint8)
    padded[10:(10+H),10:(10+W)] = image

    contours = measure.find_contours(padded, 0.5)
    if len(contours) == 0:
        return image
    if len(contours) == 1:
        contour = contours[0]
    else:
        contour = np.vstack(contours)
    cc = np.zeros_like(contour, dtype=np.int32)
    cc[:,0] = contour[:, 1]
    cc[:,1] = contour[:, 0]
    hull = cv2.convexHull(cc)
    contour = hull.reshape((1, -1, 2)) 
    cv2.fillPoly(padded, contour, 1)
    return padded[10:(10+H),10:(10+W)] 
Example #21
Source File: mask.py    From tf-cpn with MIT License 6 votes vote down vote up
def showMask(img_obj):
    img = cv2.imread(img_obj['fpath'])
    img_ori = img.copy()
    gtmasks = img_obj['gtmasks']
    n = len(gtmasks)
    print(img.shape)
    for i, mobj in enumerate(gtmasks):
        if not (type(mobj['mask']) is list):
            print("Pass a RLE mask")
            continue
        else:
            pts = np.round(np.asarray(mobj['mask'][0]))
            pts = pts.reshape(pts.shape[0] // 2, 2)
            pts = np.int32(pts)
            color = np.uint8(np.random.rand(3) * 255).tolist()
            cv2.fillPoly(img, [pts], color)
    cv2.addWeighted(img, 0.5, img_ori, 0.5, 0, img)
    cv2.imshow("Mask", img)
    cv2.waitKey(0) 
Example #22
Source File: poly_visualizer.py    From lighttrack with MIT License 6 votes vote down vote up
def draw_poly(mask, poly, track_id=-1):
    """
    Draw a polygon in the img.

    Args:
    img: np array of type np.uint8
    poly: np array of shape N x 2
    """
    if track_id == -1:
        color = (255*rand(), 255*rand(), 255*rand())
    else:
        color_list = ['purple', 'yellow', 'blue', 'green', 'red', 'skyblue', 'navyblue', 'azure', 'slate', 'chocolate', 'olive', 'orange', 'orchid']
        color_name = color_list[track_id % 13]
        color = find_color_scalar(color_name)

    poly = np.array(poly, dtype=np.int32)
    cv2.fillPoly(mask, [poly], color=color)
    return mask 
Example #23
Source File: annotate.py    From faceswap with GNU General Public License v3.0 5 votes vote down vote up
def draw_grey_out_faces(self, live_face):
        """ Grey out all faces except target """
        if not self.roi:
            return
        alpha = 0.6
        overlay = self.image.copy()
        for idx, roi in enumerate(self.roi):
            if idx != int(live_face):
                logger.trace("Greying out face: (idx: %s, roi: %s)", idx, roi)
                cv2.fillPoly(overlay, roi, (0, 0, 0))

        cv2.addWeighted(overlay, alpha, self.image, 1. - alpha, 0., self.image) 
Example #24
Source File: utils.py    From icml2017hierchvid with MIT License 5 votes vote down vote up
def drawtriangle(vertices, img_size):
  patch = np.zeros((img_size, img_size, 3))
  cv2.fillPoly(patch, np.int32(np.int32([vertices[:-1, None, :]])),
               (255, 255, 255))
  cv2.circle(patch, (int(vertices[-1, 0]), int(vertices[-1, 1])), 2,
             (255, 0, 0), -1)
  return patch.astype('uint8') 
Example #25
Source File: mesh.py    From plumo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def convex_hull (binary):
    swap_sequence = [(0, 1),  # 102
                     (0, 2),  # 201
                     (0, 2)]  # 102

    output = np.ndarray(binary.shape, dtype=binary.dtype)
    for swp1, swp2 in swap_sequence:
        N = binary.shape[0]
        print 'shape', binary.shape
        for i in range(N):
            contours = measure.find_contours(binary[i], 0.5)
            if len(contours) == 0:
                continue
            if len(contours) == 1:
                contour = contours[0]
            else:
                contour = np.vstack(contours)
            cc = np.zeros_like(contour, dtype=np.int32)
            cc[:,0] = contour[:, 1]
            cc[:,1] = contour[:, 0]
            hull = cv2.convexHull(cc)
            contour = hull.reshape((1, -1, 2)) 
            cv2.fillPoly(binary[i], contour, 1)
            #binary[i] = skimage.morphology.convex_hull_image(binary[i])
            pass
        print 'swap', swp1, swp2
        nb = np.swapaxes(binary, swp1, swp2)
        binary = np.ndarray(nb.shape, dtype=nb.dtype)
        binary[:,:] = nb[:,:]
        pass
    binary = np.swapaxes(binary, 0, 1)
    output[:,:] = binary[:,:]
    return output;
    #binary = binary_dilation(output, iterations=dilate)
    #return binary 
Example #26
Source File: image_processing.py    From DeepMosaics with GNU General Public License v3.0 5 votes vote down vote up
def find_mostlikely_ROI(mask):
    contours,hierarchy=cv2.findContours(mask, cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
    if len(contours)>0:
        areas = []
        for contour in contours:
            areas.append(cv2.contourArea(contour))
        index = areas.index(max(areas))
        mask = np.zeros_like(mask)
        mask = cv2.fillPoly(mask,[contours[index]],(255))
    return mask 
Example #27
Source File: trans_utils.py    From ocr.pytorch with MIT License 5 votes vote down vote up
def rgb2gray(filename):
    im = Image.open(filename).convert('L')
    im.show()

    new_image = Image.new("L", (im.width + 6, im.height + 6), 0)
    out_image = Image.new("L", (im.width + 6, im.height + 6), 0)

    new_image.paste(im, (3, 3, im.width + 3, im.height + 3))

    im = getcvimage(im)
    new_image = getcvimage(new_image)
    out_image = getcvimage(out_image)

    _, thresh = cv2.threshold(new_image, 0, 255, cv2.THRESH_OTSU)
    pshowone(thresh)
    image, contours, hierarchy = cv2.findContours(thresh, 3, 2)
    # cnt = contours[0]
    # hull = cv2.convexHull(cnt)
    # image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
    print(len(contours))
    cv2.polylines(out_image, contours, True, 255)
    # cv2.fillPoly(image, [cnt], 255)
    image = getpilimage(out_image)
    im = getpilimage(im)
    image = image.crop((3, 3, im.width + 3, im.height + 3))
    # char_color = image.crop((3,3,char_image.width + 3, char_image.height + 3))
    image.show()
    return 
Example #28
Source File: lane_detector.py    From ncappzoo with MIT License 5 votes vote down vote up
def filter_region(image, vertices):
    """
    Create the mask using the vertices and apply it to the input image
    """
    mask = np.zeros_like(image)
    if len(mask.shape) == 2:
        cv2.fillPoly(mask, vertices, 255)
    else:
        # in case, the input image has a channel dimension
        cv2.fillPoly(mask, vertices, (255,) * mask.shape[2])

    return cv2.bitwise_and(image, mask) 
Example #29
Source File: geometries.py    From deeposlandia with MIT License 5 votes vote down vote up
def rasterize_polygons(polygons, labels, img_height, img_width):
    """Transform a vectorized information into a numpy mask for plotting
    purpose

    Inspired from:
      - https://www.kaggle.com/lopuhin/full-pipeline-demo-poly-pixels-ml-poly

    Parameters
    ----------
    polygons : shapely.geometry.MultiPolygon
        Set of detected objects, stored as a MultiPolygon
    labels : np.array
        List of corresponding labels that describes polygon classes
    img_height : int
        Image height, in pixels
    img_width : int
        Image width, in pixels

    Returns
    -------
    numpy.array
        Rasterized polygons
    """
    img_mask = np.zeros(shape=(img_height, img_width), dtype=np.uint8)
    if not polygons:
        return img_mask
    for polygon, label in zip(polygons, labels):
        exterior = np.array(polygon.exterior.coords).round().astype(np.int32)
        interiors = [
            np.array(pi.coords).round().astype(np.int32)
            for pi in polygon.interiors
        ]
        cv2.fillPoly(img_mask, [exterior], int(label))
        cv2.fillPoly(img_mask, interiors, 0)
    return img_mask 
Example #30
Source File: lane_tracker.py    From lane_tracker with GNU General Public License v3.0 5 votes vote down vote up
def draw_lane(self, img):
        '''
        Highlight the lane the car is in and print curve radius and eccentricity onto the image.

        The method uses the polynomial graph points of the two lane lines to form the polygon that
        will be highlighted in the image.
        '''

        # Create an blank image to draw the lane on
        warped_lane = np.zeros((self.warped_size[1], self.warped_size[0])).astype(np.uint8)
        warped_lane = np.stack((warped_lane, warped_lane, warped_lane), axis=2)

        # Recast the x and y points into usable format for cv2.fillPoly()
        pts_left = np.array([np.transpose(np.vstack([self.left_avg_x, self.left_avg_y]))])
        pts_right = np.array([np.flipud(np.transpose(np.vstack([self.right_avg_x, self.right_avg_y])))])
        pts = np.hstack((pts_left, pts_right))

        # Draw the warped lane onto the blank image
        cv2.fillPoly(warped_lane, np.int_([pts]), (0, 255, 0))

        # Unwarp the lane image using the inverse perspective matrix `Minv`
        unwarped_lane = cv2.warpPerspective(warped_lane, self.Minv, (img.shape[1], img.shape[0]))

        # Draw a text field with the curve radius onto the original image
        cv2.putText(img, "Curve Radius: {} m".format(self.average_curve_radius), (20, 35), cv2.FONT_HERSHEY_SIMPLEX, fontScale=1,
                            color=(255,255,255), thickness=2, lineType=cv2.LINE_AA)
        cv2.putText(img, "Eccentricity: {:.2f} m".format(self.eccentricity), (20, 70), cv2.FONT_HERSHEY_SIMPLEX, fontScale=1,
                            color=(255,255,255), thickness=2, lineType=cv2.LINE_AA)
        if self.print_frame_count:
            cv2.putText(img, "Frame: {}".format(self.counter-1), (20, 105), cv2.FONT_HERSHEY_SIMPLEX, fontScale=1,
                                color=(255,255,255), thickness=2, lineType=cv2.LINE_AA)

        # Combine the result with the original image
        return cv2.addWeighted(img, 1, unwarped_lane, 0.3, 0)