Python cv2.pointPolygonTest() Examples

The following are 19 code examples of cv2.pointPolygonTest(). 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: ImageProcessing.py    From DAMDNet with Apache License 2.0 6 votes vote down vote up
def blendImages(src, dst, mask, featherAmount=0.2):
    #indeksy nie czarnych pikseli maski
    maskIndices = np.where(mask != 0)
    #te same indeksy tylko, ze teraz w jednej macierzy, gdzie kazdy wiersz to jeden piksel (x, y)
    maskPts = np.hstack((maskIndices[1][:, np.newaxis], maskIndices[0][:, np.newaxis]))
    faceSize = np.max(maskPts, axis=0) - np.min(maskPts, axis=0)
    featherAmount = featherAmount * np.max(faceSize)

    hull = cv2.convexHull(maskPts)
    dists = np.zeros(maskPts.shape[0])
    for i in range(maskPts.shape[0]):
        dists[i] = cv2.pointPolygonTest(hull, (maskPts[i, 0], maskPts[i, 1]), True)

    weights = np.clip(dists / featherAmount, 0, 1)

    composedImg = np.copy(dst)
    composedImg[maskIndices[0], maskIndices[1]] = weights[:, np.newaxis] * src[maskIndices[0], maskIndices[1]] + (1 - weights[:, np.newaxis]) * dst[maskIndices[0], maskIndices[1]]

    return composedImg

#uwaga, tutaj src to obraz, z ktorego brany bedzie kolor 
Example #2
Source File: ImageProcessing.py    From FaceSwap with MIT License 6 votes vote down vote up
def blendImages(src, dst, mask, featherAmount=0.2):
    #indeksy nie czarnych pikseli maski
    maskIndices = np.where(mask != 0)
    #te same indeksy tylko, ze teraz w jednej macierzy, gdzie kazdy wiersz to jeden piksel (x, y)
    maskPts = np.hstack((maskIndices[1][:, np.newaxis], maskIndices[0][:, np.newaxis]))
    faceSize = np.max(maskPts, axis=0) - np.min(maskPts, axis=0)
    featherAmount = featherAmount * np.max(faceSize)

    hull = cv2.convexHull(maskPts)
    dists = np.zeros(maskPts.shape[0])
    for i in range(maskPts.shape[0]):
        dists[i] = cv2.pointPolygonTest(hull, (maskPts[i, 0], maskPts[i, 1]), True)

    weights = np.clip(dists / featherAmount, 0, 1)

    composedImg = np.copy(dst)
    composedImg[maskIndices[0], maskIndices[1]] = weights[:, np.newaxis] * src[maskIndices[0], maskIndices[1]] + (1 - weights[:, np.newaxis]) * dst[maskIndices[0], maskIndices[1]]

    return composedImg

#uwaga, tutaj src to obraz, z ktorego brany bedzie kolor 
Example #3
Source File: HandRecognition.py    From hand-gesture-recognition-opencv with MIT License 6 votes vote down vote up
def mark_hand_center(frame_in,cont):    
    max_d=0
    pt=(0,0)
    x,y,w,h = cv2.boundingRect(cont)
    for ind_y in xrange(int(y+0.3*h),int(y+0.8*h)): #around 0.25 to 0.6 region of height (Faster calculation with ok results)
        for ind_x in xrange(int(x+0.3*w),int(x+0.6*w)): #around 0.3 to 0.6 region of width (Faster calculation with ok results)
            dist= cv2.pointPolygonTest(cont,(ind_x,ind_y),True)
            if(dist>max_d):
                max_d=dist
                pt=(ind_x,ind_y)
    if(max_d>radius_thresh*frame_in.shape[1]):
        thresh_score=True
        cv2.circle(frame_in,pt,int(max_d),(255,0,0),2)
    else:
        thresh_score=False
    return frame_in,pt,max_d,thresh_score

# 6. Find and display gesture 
Example #4
Source File: data_generation.py    From keras-ocr with MIT License 5 votes vote down vote up
def compute_transformed_contour(width, height, fontsize, M, contour, minarea=0.5):
    """Compute the permitted drawing contour
    on a padded canvas for an image of a given size.
    We assume the canvas is padded with one full image width
    and height on left and right, top and bottom respectively.

    Args:
        width: Width of image
        height: Height of image
        fontsize: Size of characters
        M: The transformation matrix
        contour: The contour to which we are limited inside
            the rectangle of size width / height
        minarea: The minimum area required for a character
            slot to qualify as being visible, expressed as
            a fraction of the untransformed fontsize x fontsize
            slot.
    """
    spacing = math.ceil(fontsize / 2)
    xslots = int(np.floor(width / spacing))
    yslots = int(np.floor(height / spacing))
    ys, xs = np.mgrid[:yslots, :xslots]
    basis = np.concatenate([xs[..., np.newaxis], ys[..., np.newaxis]], axis=-1).reshape((-1, 2))
    basis *= spacing
    slots_pretransform = np.concatenate(
        [(basis + offset)[:, np.newaxis, :]
         for offset in [[0, 0], [spacing, 0], [spacing, spacing], [0, spacing]]],
        axis=1)
    slots = cv2.perspectiveTransform(src=slots_pretransform.reshape((1, -1, 2)).astype('float32'),
                                     m=M)[0]
    inside = np.array([
        cv2.pointPolygonTest(contour=contour, pt=(x, y), measureDist=False) >= 0 for x, y in slots
    ]).reshape(-1, 4).all(axis=1)
    slots = slots.reshape(-1, 4, 2)
    areas = np.abs((slots[:, 0, 0] * slots[:, 1, 1] - slots[:, 0, 1] * slots[:, 1, 0]) +
                   (slots[:, 1, 0] * slots[:, 2, 1] - slots[:, 1, 1] * slots[:, 2, 0]) +
                   (slots[:, 2, 0] * slots[:, 3, 1] - slots[:, 2, 1] * slots[:, 3, 0]) +
                   (slots[:, 3, 0] * slots[:, 0, 1] - slots[:, 3, 1] * slots[:, 0, 0])) / 2
    slots_filtered = slots_pretransform[(areas > minarea * spacing * spacing) & inside]
    temporary_image = cv2.drawContours(image=np.zeros((height, width), dtype='uint8'),
                                       contours=slots_filtered,
                                       contourIdx=-1,
                                       color=255)
    temporary_image = cv2.dilate(src=temporary_image, kernel=np.ones((spacing, spacing)))
    newContours, _ = cv2.findContours(temporary_image,
                                      mode=cv2.RETR_TREE,
                                      method=cv2.CHAIN_APPROX_SIMPLE)
    x, y = slots_filtered[0][0]
    contour = newContours[next(
        index for index, contour in enumerate(newContours)
        if cv2.pointPolygonTest(contour=contour, pt=(x, y), measureDist=False) >= 0)][:, 0, :]
    return contour 
Example #5
Source File: img.py    From HUAWEIOCR-2019 with MIT License 5 votes vote down vote up
def is_in_contour(point, cnt):
    """tell whether a point is in contour or not. 
            In-contour here includes both the 'in contour' and 'on contour' cases.
       point:(x, y)
       cnt: a cv2 contour
    """
    # doc of pointPolygonTest: http://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=pointpolygontest#cv.PointPolygonTest
    # the last argument means only tell if in or not, without calculating the shortest distance
    in_cnt = cv2.pointPolygonTest(cnt, point, False)
    return in_cnt >= 0; 
Example #6
Source File: img.py    From HUAWEIOCR-2019 with MIT License 5 votes vote down vote up
def is_in_contour(point, cnt):
    """tell whether a point is in contour or not. 
            In-contour here includes both the 'in contour' and 'on contour' cases.
       point:(x, y)
       cnt: a cv2 contour
    """
    # doc of pointPolygonTest: http://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=pointpolygontest#cv.PointPolygonTest
    # the last argument means only tell if in or not, without calculating the shortest distance
    in_cnt = cv2.pointPolygonTest(cnt, point, False)
    return in_cnt >= 0; 
Example #7
Source File: TableRecognition.py    From OTR with GNU General Public License v3.0 5 votes vote down vote up
def is_inside_table(polygon, reference):
    """
    Determine if a given polygon is fully located inside
    This works by checking if all polygon points are within (or on the edge of)
    the reference 

    returns True if and only if polygon is fully within or identical to the reference.
    """
    brect = cv2.boxPoints(cv2.minAreaRect(polygon))
    # All points need to be inside table corners
    for point in brect:
        if cv2.pointPolygonTest(reference, tuple(point), False) < 0:
            return False  # Not in contour
    return True 
Example #8
Source File: XSegEditor.py    From DeepFaceLab with GNU General Public License v3.0 5 votes vote down vote up
def get_poly_by_pt_in_hull(self, cli_pos):
        img_pos = self.cli_to_img_pt(cli_pos)

        for poly in reversed(self.ie_polys.get_polys()):
            pts = poly.get_pts()
            if len(pts) >= 3:
                if cv2.pointPolygonTest( pts, tuple(img_pos), False) >= 0:
                    return poly

        return None 
Example #9
Source File: boardClass.py    From DE3-ROB1-CHESS with Creative Commons Attribution 4.0 International 5 votes vote down vote up
def whichSquares(self, points):
        """
        Returns the squares which a list of points lie within. This function is needed to filter out changes in the
        images that are compared which have nothing to do with the game, e.g. an arm.
        """
        matches = []
        for square in self.squares:
            for point in points:
                dist = cv2.pointPolygonTest(square.contours,point,False)
                if dist >= 0:
                    matches.append(square)

        return matches 
Example #10
Source File: process.py    From edusense with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_pts_of_interest(keypoints, area_of_interest):
    for i in range(int(len(keypoints)/3)):
        is_of_interest = cv2.pointPolygonTest(area_of_interest, (keypoints[3*i], keypoints[3*i+1]), False) >= 0
        keypoints[3*i] = keypoints[3*i] if is_of_interest else 0
        keypoints[3*i+1] = keypoints[3*i+1] if is_of_interest else 0
        keypoints[3*i+2] = keypoints[3*i+2] if is_of_interest else 0

    return keypoints 
Example #11
Source File: object_finder.py    From baxter_demos with Apache License 2.0 5 votes vote down vote up
def getEncirclingContour(self, contours):
        for contour in contours:
            if cv2.pointPolygonTest(contour, self.point, False) > 0:
                return contour 
Example #12
Source File: detection.py    From TextSnake.pytorch with MIT License 5 votes vote down vote up
def in_contour(self, cont, point):
        """
        utility function for judging whether `point` is in the `contour`
        :param cont: cv2.findCountour result
        :param point: 2d coordinate (x, y)
        :return:
        """
        x, y = point
        return cv2.pointPolygonTest(cont, (x, y), False) > 0 
Example #13
Source File: detection.py    From TextSnake.pytorch with MIT License 5 votes vote down vote up
def find_innerpoint(self, cont):
        """
        generate an inner point of input polygon using mean of x coordinate by:
        1. calculate mean of x coordinate(xmean)
        2. calculate maximum and minimum of y coordinate(ymax, ymin)
        3. iterate for each y in range (ymin, ymax), find first segment in the polygon
        4. calculate means of segment
        :param cont: input polygon
        :return:
        """

        xmean = cont[:, 0, 0].mean()
        ymin, ymax = cont[:, 0, 1].min(), cont[:, 0, 1].max()
        found = False
        found_y = []
        #
        for i in np.arange(ymin - 1, ymax + 1, 0.5):
            # if in_poly > 0, (xmean, i) is in `cont`
            in_poly = cv2.pointPolygonTest(cont, (xmean, i), False)
            if in_poly > 0:
                found = True
                found_y.append(i)
            # first segment found
            if in_poly < 0 and found:
                break

        if len(found_y) > 0:
            return (xmean, np.array(found_y).mean())

        # if cannot find using above method, try each point's neighbor
        else:
            for p in range(len(cont)):
                point = cont[p, 0]
                for i in range(-1, 2, 1):
                    for j in range(-1, 2, 1):
                        test_pt = point + [i, j]
                        if cv2.pointPolygonTest(cont, (test_pt[0], test_pt[1]), False) > 0:
                            return test_pt 
Example #14
Source File: meta_artificial.py    From Text-Recognition with GNU Lesser General Public License v2.1 5 votes vote down vote up
def inside_point(self, point, rect):

		# point is a list (x, y)
		# rect is a contour with shape [4, 2]

		rect = rect.reshape([4, 1, 2]).astype(np.int64)

		dist = cv2.pointPolygonTest(rect,(point[0], point[1]),True)

		if dist>=0:
			# print(dist)
			return True
		else:
			return False 
Example #15
Source File: utils.py    From Text-Recognition with GNU Lesser General Public License v2.1 5 votes vote down vote up
def inside_point(point, rect):

	# point is a list (x, y)
	# rect is a contour with shape [4, 2]

	rect = rect.reshape([4, 1, 2]).astype(np.int64)

	dist = cv2.pointPolygonTest(rect,(point[0], point[1]),True)

	if dist>0:
		# print(dist)
		return True
	else:
		return False 
Example #16
Source File: img.py    From HUAWEIOCR-2019 with MIT License 5 votes vote down vote up
def is_in_contour(point, cnt):
    """tell whether a point is in contour or not. 
            In-contour here includes both the 'in contour' and 'on contour' cases.
       point:(x, y)
       cnt: a cv2 contour
    """
    # doc of pointPolygonTest: http://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=pointpolygontest#cv.PointPolygonTest
    # the last argument means only tell if in or not, without calculating the shortest distance
    in_cnt = cv2.pointPolygonTest(cnt, point, False)
    return in_cnt >= 0; 
Example #17
Source File: training_data.py    From faceswap with GNU General Public License v3.0 4 votes vote down vote up
def _random_warp_landmarks(self, batch, batch_src_points, batch_dst_points):
        """ From dfaker. Warp the image to a similar set of landmarks from the opposite side """
        logger.trace("Randomly warping landmarks")
        edge_anchors = self._constants["warp_lm_edge_anchors"]
        grids = self._constants["warp_lm_grids"]
        slices = self._constants["tgt_slices"]

        batch_dst = (batch_dst_points + np.random.normal(size=batch_dst_points.shape,
                                                         scale=2.0))

        face_cores = [cv2.convexHull(np.concatenate([src[17:], dst[17:]], axis=0))
                      for src, dst in zip(batch_src_points.astype("int32"),
                                          batch_dst.astype("int32"))]

        batch_src = np.append(batch_src_points, edge_anchors, axis=1)
        batch_dst = np.append(batch_dst, edge_anchors, axis=1)

        rem_indices = [list(set(idx for fpl in (src, dst)
                                for idx, (pty, ptx) in enumerate(fpl)
                                if cv2.pointPolygonTest(face_core, (pty, ptx), False) >= 0))
                       for src, dst, face_core in zip(batch_src[:, :18, :],
                                                      batch_dst[:, :18, :],
                                                      face_cores)]
        batch_src = [np.delete(src, idxs, axis=0) for idxs, src in zip(rem_indices, batch_src)]
        batch_dst = [np.delete(dst, idxs, axis=0) for idxs, dst in zip(rem_indices, batch_dst)]

        grid_z = np.array([griddata(dst, src, (grids[0], grids[1]), method="linear")
                           for src, dst in zip(batch_src, batch_dst)])
        maps = grid_z.reshape(self._batchsize,
                              self._training_size,
                              self._training_size,
                              2).astype("float32")
        warped_batch = np.array([cv2.remap(image,
                                           map_[..., 1],
                                           map_[..., 0],
                                           cv2.INTER_LINEAR,
                                           cv2.BORDER_TRANSPARENT)
                                 for image, map_ in zip(batch, maps)])
        warped_batch = np.array([cv2.resize(image[slices, slices, :],
                                            (self._input_size, self._input_size),
                                            cv2.INTER_AREA)
                                 for image in warped_batch])
        logger.trace("Warped batch shape: %s", warped_batch.shape)
        return warped_batch 
Example #18
Source File: Features.py    From SimpleCV2 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _pointInsidePolygon(self,point,polygon):
        """
        returns true if tuple point (x,y) is inside polygon of the form ((a,b),(c,d),...,(a,b)) the polygon should be closed

        """
        # try:
        #     import cv2
        # except:
        #     logger.warning("Unable to import cv2")
        #     return False

        if( len(polygon) < 3 ):
            logger.warning("feature._pointInsidePolygon - this is not a valid polygon")
            return False

        if( not isinstance(polygon,list)):
            logger.warning("feature._pointInsidePolygon - this is not a valid polygon")
            return False

        #if( not isinstance(point,tuple) ):
            #if( len(point) == 2 ):
            #    point = tuple(point)
            #else:
            #    logger.warning("feature._pointInsidePolygon - this is not a valid point")
            #    return False
        #if( cv2.__version__ == '$Rev:4557'):
        counter = 0
        retVal = True
        p1 = None
        #print "point: " + str(point)
        poly = copy.deepcopy(polygon)
        poly.append(polygon[0])
        #for p2 in poly:
        N = len(poly)
        p1 = poly[0]
        for i in range(1,N+1):
            p2 = poly[i%N]
            if( point[1] > np.min((p1[1],p2[1])) ):
                if( point[1] <= np.max((p1[1],p2[1])) ):
                    if( point[0] <= np.max((p1[0],p2[0])) ):
                        if( p1[1] != p2[1] ):
                            test = float((point[1]-p1[1])*(p2[0]-p1[0]))/float(((p2[1]-p1[1])+p1[0]))
                            if( p1[0] == p2[0] or point[0] <= test ):
                                counter = counter + 1
            p1 = p2

        if( counter % 2 == 0 ):
            retVal = False
            return retVal
        return retVal
        #else:
        #    result = cv2.pointPolygonTest(np.array(polygon,dtype='float32'),point,0)
        #    return result > 0 
Example #19
Source File: image_augmentation.py    From df with Mozilla Public License 2.0 4 votes vote down vote up
def random_warp_src_dest( in_image,srcPoints,destPoints ):

  source = srcPoints
  destination = (destPoints.copy().astype('float')+numpy.random.normal( size=(destPoints.shape), scale= 2 ))
  destination = destination.astype('int')

  faceCore =cv2.convexHull( numpy.concatenate([source[17:],destination[17:]], axis=0).astype(int) )

  source = [(y,x) for x,y in source]+edgeAnchors
  destination = [(y,x) for x,y in destination]+edgeAnchors


  indeciesToRemove = set()
  for fpl in source,destination:
    for i,(y,x) in enumerate(fpl):
      if i>17:
        break
      elif cv2.pointPolygonTest(faceCore,(y,x),False) >= 0:
        indeciesToRemove.add(i)

  for i in sorted(indeciesToRemove,reverse=True):
    source.pop(i)
    destination.pop(i)

  grid_z = griddata( destination,source, (grid_x, grid_y), method='linear')
  map_x = numpy.append([], [ar[:,1] for ar in grid_z]).reshape(256,256)
  map_y = numpy.append([], [ar[:,0] for ar in grid_z]).reshape(256,256)
  map_x_32 = map_x.astype('float32')
  map_y_32 = map_y.astype('float32')

  warped = cv2.remap(in_image[:,:,:3], map_x_32, map_y_32, cv2.INTER_LINEAR,cv2.BORDER_TRANSPARENT )

  target_mask = in_image[:,:,3].reshape((256,256,1))
  target_image = in_image[:,:,:3]

  warped       = cv2.resize( warped[ 128-120:128+120,128-120:128+120,:]         ,(64,64),cv2.INTER_AREA)
  target_image = cv2.resize( target_image[ 128-120:128+120,128-120:128+120,: ]  ,(64*2,64*2),cv2.INTER_AREA)
  target_mask  = cv2.resize( target_mask[ 128-120:128+120,128-120:128+120,: ]   ,(64*2,64*2),cv2.INTER_AREA).reshape((64*2,64*2,1))

  return warped,target_image,target_mask

# get pair of random warped images from aligened face image