Python cv2.contourArea() Examples

The following are 30 code examples of cv2.contourArea(). 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: chapter2.py    From OpenCV-Computer-Vision-Projects-with-Python with MIT License 19 votes vote down vote up
def FindHullDefects(self, segment):
        _,contours,hierarchy = cv2.findContours(segment, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

        # find largest area contour
        max_area = -1
        for i in range(len(contours)):
            area = cv2.contourArea(contours[i])
            if area>max_area:
                cnt = contours[i]
                max_area = area

        cnt = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
        hull = cv2.convexHull(cnt, returnPoints=False)
        defects = cv2.convexityDefects(cnt, hull)

        return [cnt,defects] 
Example #2
Source File: segment.py    From gesture-recognition with MIT License 12 votes vote down vote up
def segment(image, threshold=25):
    global bg
    # find the absolute difference between background and current frame
    diff = cv2.absdiff(bg.astype("uint8"), image)

    # threshold the diff image so that we get the foreground
    thresholded = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)[1]

    # get the contours in the thresholded image
    (_, cnts, _) = cv2.findContours(thresholded.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # return None, if no contours detected
    if len(cnts) == 0:
        return
    else:
        # based on contour area, get the maximum contour which is the hand
        segmented = max(cnts, key=cv2.contourArea)
        return (thresholded, segmented)

#-----------------
# MAIN FUNCTION
#----------------- 
Example #3
Source File: thresholding.py    From smashscan with MIT License 12 votes vote down vote up
def contour_filter(self, frame):
        _, contours, _ = cv2.findContours(frame,
            cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        new_frame = np.zeros(frame.shape, np.uint8)
        for i, contour in enumerate(contours):
            c_area = cv2.contourArea(contour)
            if self.contour_min_area <= c_area <= self.contour_max_area:
                mask = np.zeros(frame.shape, np.uint8)
                cv2.drawContours(mask, contours, i, 255, cv2.FILLED)
                mask = cv2.bitwise_and(frame, mask)
                new_frame = cv2.bitwise_or(new_frame, mask)
        frame = new_frame

        if self.contour_disp_flag:
            frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
            cv2.drawContours(frame, contours, -1, (255, 0, 0), 1)

        return frame


    # A number of methods corresponding to the various trackbars available. 
Example #4
Source File: squares.py    From OpenCV-Python-Tutorial with MIT License 9 votes vote down vote up
def find_squares(img):
    img = cv2.GaussianBlur(img, (5, 5), 0)
    squares = []
    for gray in cv2.split(img):
        for thrs in xrange(0, 255, 26):
            if thrs == 0:
                bin = cv2.Canny(gray, 0, 50, apertureSize=5)
                bin = cv2.dilate(bin, None)
            else:
                retval, bin = cv2.threshold(gray, thrs, 255, cv2.THRESH_BINARY)
            bin, contours, hierarchy = cv2.findContours(bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
            for cnt in contours:
                cnt_len = cv2.arcLength(cnt, True)
                cnt = cv2.approxPolyDP(cnt, 0.02*cnt_len, True)
                if len(cnt) == 4 and cv2.contourArea(cnt) > 1000 and cv2.isContourConvex(cnt):
                    cnt = cnt.reshape(-1, 2)
                    max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in xrange(4)])
                    if max_cos < 0.1:
                        squares.append(cnt)
    return squares 
Example #5
Source File: size_detector.py    From gaps with MIT License 9 votes vote down vote up
def _find_size_candidates(self, image):
        binary_image = self._filter_image(image)

        _, contours, _ = cv2.findContours(binary_image,
                                          cv2.RETR_LIST,
                                          cv2.CHAIN_APPROX_SIMPLE)

        size_candidates = []
        for contour in contours:
            bounding_rect = cv2.boundingRect(contour)
            contour_area = cv2.contourArea(contour)
            if self._is_valid_contour(contour_area, bounding_rect):
                candidate = (bounding_rect[2] + bounding_rect[3]) / 2
                size_candidates.append(candidate)

        return size_candidates 
Example #6
Source File: tracking.py    From OpenCV-Computer-Vision-Projects-with-Python with MIT License 7 votes vote down vote up
def _append_boxes_from_saliency(self, proto_objects_map, box_all):
        """Adds to the list all bounding boxes found with the saliency map

            A saliency map is used to find objects worth tracking in each
            frame. This information is combined with a mean-shift tracker
            to find objects of relevance that move, and to discard everything
            else.

            :param proto_objects_map: proto-objects map of the current frame
            :param box_all: append bounding boxes from saliency to this list
            :returns: new list of all collected bounding boxes
        """
        # find all bounding boxes in new saliency map
        box_sal = []
        cnt_sal, _ = cv2.findContours(proto_objects_map, 1, 2)
        for cnt in cnt_sal:
            # discard small contours
            if cv2.contourArea(cnt) < self.min_cnt_area:
                continue

            # otherwise add to list of boxes found from saliency map
            box = cv2.boundingRect(cnt)
            box_all.append(box)

        return box_all 
Example #7
Source File: coco_seg_fast.py    From PolarMask with Apache License 2.0 7 votes vote down vote up
def get_single_centerpoint(self, mask):
        contour, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
        contour.sort(key=lambda x: cv2.contourArea(x), reverse=True)  # only save the biggest one

        '''debug IndexError: list index out of range'''
        count = contour[0][:, 0, :]
        try:
            center = self.get_centerpoint(count)
        except:
            x,y = count.mean(axis=0)
            center=[int(x), int(y)]
            
        #decrease the number of contour, to speed up
        # 360 points should ok, the performance drop very tiny.
        max_points = 360
        if len(contour[0]) > max_points:
            compress_rate = len(contour[0]) // max_points
            contour[0] = contour[0][::compress_rate, ...]
        return center, contour 
Example #8
Source File: SudokuExtractor.py    From SolveSudoku with MIT License 7 votes vote down vote up
def find_corners_of_largest_polygon(img):
	"""Finds the 4 extreme corners of the largest contour in the image."""
	opencv_version = cv2.__version__.split('.')[0]
	if opencv_version == '3':
		_, contours, h = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)  # Find contours
	else:
		contours, h = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)  # Find contours
	contours = sorted(contours, key=cv2.contourArea, reverse=True)  # Sort by area, descending
	polygon = contours[0]  # Largest image

	# Use of `operator.itemgetter` with `max` and `min` allows us to get the index of the point
	# Each point is an array of 1 coordinate, hence the [0] getter, then [0] or [1] used to get x and y respectively.

	# Bottom-right point has the largest (x + y) value
	# Top-left has point smallest (x + y) value
	# Bottom-left point has smallest (x - y) value
	# Top-right point has largest (x - y) value
	bottom_right, _ = max(enumerate([pt[0][0] + pt[0][1] for pt in polygon]), key=operator.itemgetter(1))
	top_left, _ = min(enumerate([pt[0][0] + pt[0][1] for pt in polygon]), key=operator.itemgetter(1))
	bottom_left, _ = min(enumerate([pt[0][0] - pt[0][1] for pt in polygon]), key=operator.itemgetter(1))
	top_right, _ = max(enumerate([pt[0][0] - pt[0][1] for pt in polygon]), key=operator.itemgetter(1))

	# Return an array of all 4 points using the indices
	# Each point is in its own array of one coordinate
	return [polygon[top_left][0], polygon[top_right][0], polygon[bottom_right][0], polygon[bottom_left][0]] 
Example #9
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 #10
Source File: load_saved_model.py    From document-ocr with Apache License 2.0 7 votes vote down vote up
def mask_to_bbox(mask, image, num_class, area_threhold=0, out_path=None, out_file_name=None):
  bbox_list = []
  im = copy.copy(image)
  mask = mask.astype(np.uint8)
  for i in range(1, num_class, 1):
    c_bbox_list = []
    c_mask = np.zeros_like(mask)
    c_mask[np.where(mask==i)] = 255
    bimg , countours, hier = cv2.findContours(c_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for cnt in countours:
      area = cv2.contourArea(cnt)
      if area < area_threhold:
        continue
      epsilon = 0.005 * cv2.arcLength(cnt,True)
      approx = cv2.approxPolyDP(cnt,epsilon,True)
      (x, y, w, h) = cv2.boundingRect(approx)
      c_bbox_list.append([x,  y, x+w, y+h])
      if out_path is not None:
        color = COLOR_LIST[i-1]
        im=cv2.rectangle(im, pt1=(x, y), pt2=(x+w, y+h),color=color, thickness=2)
    bbox_list.append(c_bbox_list)
  if out_path is not None:
    outf = os.path.join(out_path, out_file_name)
    cv2.imwrite(outf, im)
  return bbox_list 
Example #11
Source File: losses_win.py    From R3Det_Tensorflow with MIT License 6 votes vote down vote up
def iou_rotate_calculate2(boxes1, boxes2):
    ious = []
    if boxes1.shape[0] != 0:
        area1 = boxes1[:, 2] * boxes1[:, 3]
        area2 = boxes2[:, 2] * boxes2[:, 3]

        for i in range(boxes1.shape[0]):
            temp_ious = []
            r1 = ((boxes1[i][0], boxes1[i][1]), (boxes1[i][2], boxes1[i][3]), boxes1[i][4])
            r2 = ((boxes2[i][0], boxes2[i][1]), (boxes2[i][2], boxes2[i][3]), boxes2[i][4])

            int_pts = cv2.rotatedRectangleIntersection(r1, r2)[1]
            if int_pts is not None:
                order_pts = cv2.convexHull(int_pts, returnPoints=True)

                int_area = cv2.contourArea(order_pts)

                inter = int_area * 1.0 / (area1[i] + area2[i] - int_area)
                temp_ious.append(inter)
            else:
                temp_ious.append(0.0)
            ious.append(temp_ious)

    return np.array(ious, dtype=np.float32) 
Example #12
Source File: coco_seg.py    From PolarMask with Apache License 2.0 6 votes vote down vote up
def get_single_centerpoint(self, mask):
        contour, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
        contour.sort(key=lambda x: cv2.contourArea(x), reverse=True) #only save the biggest one
        '''debug IndexError: list index out of range'''
        count = contour[0][:, 0, :]
        try:
            center = self.get_centerpoint(count)
        except:
            x,y = count.mean(axis=0)
            center=[int(x), int(y)]

        # max_points = 360
        # if len(contour[0]) > max_points:
        #     compress_rate = len(contour[0]) // max_points
        #     contour[0] = contour[0][::compress_rate, ...]
        return center, contour 
Example #13
Source File: siam_mask_tracker.py    From models with MIT License 6 votes vote down vote up
def _mask_post_processing(mask, center_pos, size, track_mask_threshold):
    target_mask = (mask > track_mask_threshold)
    target_mask = target_mask.astype(np.uint8)
    if cv2.__version__[-5] == '4':
        contours, _ = cv2.findContours(target_mask,
                                       cv2.RETR_EXTERNAL,
                                       cv2.CHAIN_APPROX_NONE)
    else:
        _, contours, _ = cv2.findContours(
                target_mask,
                cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    cnt_area = [cv2.contourArea(cnt) for cnt in contours]
    if len(contours) != 0 and np.max(cnt_area) > 100:
        contour = contours[np.argmax(cnt_area)] 
        polygon = contour.reshape(-1, 2)
        prbox = cv2.boxPoints(cv2.minAreaRect(polygon))
        rbox_in_img = prbox
    else:  # empty mask
        location = cxy_wh_2_rect(center_pos, size)
        rbox_in_img = np.array([[location[0], location[1]],
                    [location[0] + location[2], location[1]],
                    [location[0] + location[2], location[1] + location[3]],
                    [location[0], location[1] + location[3]]])
    return rbox_in_img 
Example #14
Source File: utils.py    From Text-Recognition with GNU Lesser General Public License v2.1 6 votes vote down vote up
def remove_small_boxes(contours, min_area, max_area=None):

	"""
	input - contour, min_area, max_are
	return - thresholded contour
	"""

	contours = get_rotated_bbox(contours)

	return_contours = []

	for i in range(len(contours)):
		area = cv2.contourArea(contours[i])
		if area > min_area:
			if max_area!=None:
				if area < max_area:
					return_contours.append(contours[i])
			else:
				return_contours.append(contours[i])

	return return_contours

	#Removes contours whose area is smaller than specified value or larger than max_area(if specified), and returns the remaining contours 
Example #15
Source File: HandRecognition.py    From hand-gesture-recognition-opencv with MIT License 6 votes vote down vote up
def hand_contour_find(contours):
    max_area=0
    largest_contour=-1
    for i in range(len(contours)):
        cont=contours[i]
        area=cv2.contourArea(cont)
        if(area>max_area):
            max_area=area
            largest_contour=i
    if(largest_contour==-1):
        return False,0
    else:
        h_contour=contours[largest_contour]
        return True,h_contour

# 4. Detect & mark fingers 
Example #16
Source File: detect_tables.py    From namsel with MIT License 6 votes vote down vote up
def find_boxes(tiff_fl, blur=False):
    im = Image.open(tiff_fl).convert('L')
    a = np.asarray(im)
    if blur:
        a = cv.GaussianBlur(a, (5, 5), 0)
    contours, hierarchy = cv.findContours(a.copy(), mode=cv.RETR_TREE, method=cv.CHAIN_APPROX_SIMPLE)
    border_boxes = []
#     n = np.ones_like(a)
    for j,cnt in enumerate(contours):
        cnt_len = cv.arcLength(cnt, True)
        orig_cnt = cnt.copy()
        cnt = cv.approxPolyDP(cnt, 0.02*cnt_len, True)
        if len(cnt) == 4 and ((a.shape[0]-3) * (a.shape[1] -3)) > cv.contourArea(cnt) > 1000 and cv.isContourConvex(cnt):
            cnt = cnt.reshape(-1, 2)
            max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in xrange(4)])
            if max_cos < 0.1:
                b = cv.boundingRect(orig_cnt)
                x,y,w,h = b
                border_boxes.append(b)
#                 cv.rectangle(n, (x,y), (x+w, y+h), 0)
#                 cv.drawContours(n, [cnt], -1,0, thickness = 5)
#     Image.fromarray(n*255).show()
    return border_boxes 
Example #17
Source File: recognize.py    From gesture-recognition with MIT License 6 votes vote down vote up
def segment(image, threshold=25):
    global bg
    # find the absolute difference between background and current frame
    diff = cv2.absdiff(bg.astype("uint8"), image)

    # threshold the diff image so that we get the foreground
    thresholded = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)[1]

    # get the contours in the thresholded image
    (_, cnts, _) = cv2.findContours(thresholded.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # return None, if no contours detected
    if len(cnts) == 0:
        return
    else:
        # based on contour area, get the maximum contour which is the hand
        segmented = max(cnts, key=cv2.contourArea)
        return (thresholded, segmented)

#--------------------------------------------------------------
# To count the number of fingers in the segmented hand region
#-------------------------------------------------------------- 
Example #18
Source File: dataload.py    From TextSnake.pytorch with MIT License 6 votes vote down vote up
def __init__(self, points, orient, text):
        self.orient = orient
        self.text = text

        remove_points = []

        if len(points) > 4:
            # remove point if area is almost unchanged after removing it
            ori_area = cv2.contourArea(points)
            for p in range(len(points)):
                # attempt to remove p
                index = list(range(len(points)))
                index.remove(p)
                area = cv2.contourArea(points[index])
                if np.abs(ori_area - area) / ori_area < 0.017 and len(points) - len(remove_points) > 4:
                    remove_points.append(p)
            self.points = np.array([point for i, point in enumerate(points) if i not in remove_points])
        else:
            self.points = np.array(points) 
Example #19
Source File: motion.py    From object-detection with MIT License 6 votes vote down vote up
def filter_prediction(self, output, image):
        if len(output) < 2:
            return pd.DataFrame()
        else:
            df = pd.DataFrame(output)
            df = df.assign(
                    area=lambda x: df[0].apply(lambda x: cv2.contourArea(x)),
                    bounding=lambda x: df[0].apply(lambda x: cv2.boundingRect(x))
                    )
            df = df[df['area'] > MIN_AREA]
            df_filtered = pd.DataFrame(
                    df['bounding'].values.tolist(), columns=['x1', 'y1', 'w', 'h'])
            df_filtered = df_filtered.assign(
                    x1=lambda x: x['x1'].clip(0),
                    y1=lambda x: x['y1'].clip(0),
                    x2=lambda x: (x['x1'] + x['w']),
                    y2=lambda x: (x['y1'] + x['h']),
                    label=lambda x: x.index.astype(str),
                    class_name=lambda x: x.index.astype(str),
                    )
            return df_filtered 
Example #20
Source File: judge_color_center.py    From Python-Code with MIT License 5 votes vote down vote up
def getColor(frame):
	hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
	maxsum = 0
	color = None
	color_dict = colorList.getColorList()

	# 对每个颜色进行判断
	for d in color_dict:
		# 根据阈值构建掩膜
		mask = cv2.inRange(hsv, color_dict[d][0], color_dict[d][1])
		# 腐蚀操作
		mask = cv2.erode(mask, None, iterations=2)
		# 膨胀操作,其实先腐蚀再膨胀的效果是开运算,去除噪点
		mask = cv2.dilate(mask, None, iterations=2)	
		img, cnts, hiera = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
		
		# 有轮廓才进行后面的判断
		if len(cnts) > 0:	
			# 计算识别区域的面积
			sum = 0
			for c in cnts:
				sum += cv2.contourArea(c)
			
			# 找到最大面积并找到质心
			if sum > maxsum :
				maxsum = sum	
				if maxsum != 0:
					color = d
				else:
					color = None
				# 找到面积最大的轮廓
				c = max(cnts, key = cv2.contourArea)
				# 确定面积最大的轮廓的外接圆
				((x, y), radius) = cv2.minEnclosingCircle(c)
				# 计算轮廓的矩
				M = cv2.moments(c)
				# 计算质心
				center = (int(M["m10"]/M["m00"]), int(M["m01"]/M["m00"]))
 
	return color, center 
Example #21
Source File: judge_single_color.py    From Python-Code with MIT License 5 votes vote down vote up
def getColor(frame):
	hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
	maxsum = 0
	color = None
	color_dict = color_list.getColorList()

	# 对每个颜色进行判断
	for d in color_dict:
		# 根据阈值构建掩膜
		mask = cv2.inRange(hsv, color_dict[d][0], color_dict[d][1])
		# 腐蚀操作
		mask = cv2.erode(mask, None, iterations=2)
		# 膨胀操作,其实先腐蚀再膨胀的效果是开运算,去除噪点
		mask = cv2.dilate(mask, None, iterations=2)	
		img, cnts, hiera = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
		
		# 有轮廓才进行后面的判断
		if len(cnts) > 0:	
			# 计算识别区域的面积
			sum = 0
			for c in cnts:
				sum += cv2.contourArea(c)
			
			# 找到最大面积并找到质心
			if sum > maxsum :
				maxsum = sum	
				if maxsum != 0:
					color = d
				else:
					color = None
 
	return color 
Example #22
Source File: handdetector.py    From deep-prior with GNU General Public License v3.0 5 votes vote down vote up
def track(self, com, size=(250, 250, 250), dsize=(128, 128), doHandSize=True):
        """
        Detect the hand as closest object to camera
        :param size: bounding box size
        :return: center of mass of hand
        """

        # calculate boundaries
        xstart, xend, ystart, yend, zstart, zend = self.comToBounds(com, size)

        # crop patch from source
        cropped = self.getCrop(self.dpt, xstart, xend, ystart, yend, zstart, zend)

        # predict movement of CoM
        if self.refineNet is not None and self.importer is not None:
            rz = self.resizeCrop(cropped, dsize)
            newCom3D = self.refineCoM(rz, size, com) + self.importer.jointImgTo3D(com)
            com = self.importer.joint3DToImg(newCom3D)
            if numpy.allclose(com, 0.):
                com[2] = cropped[cropped.shape[0]//2, cropped.shape[1]//2]
        else:
            raise RuntimeError("Need refineNet for this")

        if doHandSize is True:
            # refined contour for size estimation
            zstart = com[2] - size[2] / 2.
            zend = com[2] + size[2] / 2.
            part_ref = self.dpt.copy()
            part_ref[part_ref < zstart] = 0
            part_ref[part_ref > zend] = 0
            part_ref[part_ref != 0] = 10  # set to something
            ret, thresh_ref = cv2.threshold(part_ref, 1, 255, cv2.THRESH_BINARY)
            contours_ref, _ = cv2.findContours(thresh_ref.astype(dtype=numpy.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
            # find the largest contour
            areas = [cv2.contourArea(cc) for cc in contours_ref]
            c_max = numpy.argmax(areas)

            # final result
            return com, self.estimateHandsize(contours_ref[c_max], com, size)
        else:
            return com, size 
Example #23
Source File: object_finder.py    From baxter_demos with Apache License 2.0 5 votes vote down vote up
def getLargestContour(self, contours):
        maxpair = (None, 0)
        if len(contours) == 0:
            raise Exception("Got no contours in getLargestContour")
        for contour in contours:
            area = cv2.contourArea(contour)
            if area > maxpair[1]:
                maxpair = (contour, area)
        return maxpair[0] 
Example #24
Source File: helpers.py    From Color-Tracker with MIT License 5 votes vote down vote up
def sort_contours_by_area(contours: np.ndarray, descending: bool = True) -> np.ndarray:
    if len(contours) > 0:
        contours = sorted(contours, key=cv2.contourArea, reverse=descending)
    return contours 
Example #25
Source File: object_detection_using_color.py    From Hands-On-Machine-Learning-with-OpenCV-4 with MIT License 5 votes vote down vote up
def locate_object(frame, object_hist):

    # convert to HSV
    hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # apply back projection to image using object_hist as
    # the model histogram
    object_segment = cv2.calcBackProject(
        [hsv_frame], [0, 1], object_hist, [0, 180, 0, 256], 1)

    # find the contours
    img, contours, _ = cv2.findContours(
        object_segment,
        cv2.RETR_TREE,
        cv2.CHAIN_APPROX_SIMPLE)

    flag = None
    max_area = 0

    # find the contour with the greatest area
    for (i, c) in enumerate(contours):
        area = cv2.contourArea(c)
        if area > max_area:
            max_area = area
            flag = i

    # get the rectangle
    if flag is not None and max_area > 1000:
        cnt = contours[flag]
        coords = cv2.boundingRect(cnt)
        return coords

    return None


# compute the color histogram 
Example #26
Source File: nms_rotate.py    From remote_sensing_object_detection_2019 with MIT License 5 votes vote down vote up
def nms_rotate_cpu(boxes, scores, iou_threshold, max_output_size):

    keep = []

    order = scores.argsort()[::-1]
    num = boxes.shape[0]

    suppressed = np.zeros((num), dtype=np.int)

    for _i in range(num):
        if len(keep) >= max_output_size:
            break

        i = order[_i]
        if suppressed[i] == 1:
            continue
        keep.append(i)
        r1 = ((boxes[i, 0], boxes[i, 1]), (boxes[i, 2], boxes[i, 3]), boxes[i, 4])
        area_r1 = boxes[i, 2] * boxes[i, 3]
        for _j in range(_i + 1, num):
            j = order[_j]
            if suppressed[i] == 1:
                continue
            r2 = ((boxes[j, 0], boxes[j, 1]), (boxes[j, 2], boxes[j, 3]), boxes[j, 4])
            area_r2 = boxes[j, 2] * boxes[j, 3]
            inter = 0.0

            int_pts = cv2.rotatedRectangleIntersection(r1, r2)[1]
            if int_pts is not None:
                order_pts = cv2.convexHull(int_pts, returnPoints=True)

                int_area = cv2.contourArea(order_pts)

                inter = int_area * 1.0 / (area_r1 + area_r2 - int_area + cfgs.EPSILON)

            if inter >= iou_threshold:
                suppressed[j] = 1

    return np.array(keep, np.int64) 
Example #27
Source File: helpers.py    From Color-Tracker with MIT License 5 votes vote down vote up
def filter_contours_by_area(contours: np.ndarray, min_area: float = 0, max_area: float = np.inf) -> np.ndarray:
    if len(contours) == 0:
        return np.array([])

    def _keep_contour(c):
        area = cv2.contourArea(c)
        if area <= min_area:
            return False
        if area >= max_area:
            return False
        return True

    return np.array(list(filter(_keep_contour, contours))) 
Example #28
Source File: auto_marker.py    From lightnet with MIT License 5 votes vote down vote up
def update_image(image_id, category_id = 0, image_filenames=[], enable_vis=True, enable_marker_dump=False):
    try:
        global contours, hierarchy, img, gray, g_image_filenames
        if len(image_filenames) > 0:
            g_image_filenames=image_filenames
        img=cv.imread(g_image_filenames[image_id])
        # print(g_image_filenames[image_id])
        cv.setTrackbarPos('image', 'marker', image_id)

        gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
        gray[np.where(gray <= [3])] = [187]
        gray = cv.medianBlur(gray, 11)

        if enable_vis:
            cv.imshow('gray', gray)

        if CANNY_MODE:
            thrs1 = cv.getTrackbarPos('thrs1', 'marker')
            thrs2 = cv.getTrackbarPos('thrs2', 'marker')
            bin = cv.Canny(gray, thrs1, thrs2, apertureSize=5)
        else:
            bin = cv.adaptiveThreshold(
                gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY_INV, 31, 10)

        if enable_vis:
            cv.imshow('bin', bin)

        _, contours0, hierarchy = cv.findContours(
            bin.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
        contours = [cnt for cnt in contours0 if cv.contourArea(cnt) > 200]

        if enable_vis:
            cv.imshow('image', img)
        update_contour(category_id, image_id, enable_vis, enable_marker_dump)
    except Exception:
        import traceback
        traceback.print_exc()
        raise 
Example #29
Source File: ocr.py    From smashscan with MIT License 5 votes vote down vote up
def contour_test(img):
    _, contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL,
        cv2.CHAIN_APPROX_SIMPLE)
    img_d = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    cv2.drawContours(img_d, contours, -1, (255, 0, 0), 2)
    cv2.imshow('test', img_d)
    cv2.waitKey(0)
    res = np.zeros(img.shape, np.uint8)

    for i, contour in enumerate(contours):
        img_d = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
        cv2.drawContours(img_d, contour, -1, (255, 0, 0), 3)

        moment = cv2.moments(contour)
        if moment['m00']: # Removes single points
            cx = int(moment['m10']/moment['m00'])
            cy = int(moment['m01']/moment['m00'])
            print("Center: {}".format((cx, cy)))
            cv2.circle(img_d, (cx, cy), 3, (0, 0, 255), -1)

        print("Area: {}".format(cv2.contourArea(contour)))
        print("Permeter: {} ".format(cv2.arcLength(contour, True)))

        cv2.imshow('test', img_d)
        cv2.waitKey(0)

        # The result displayed is an accumulation of previous contours.
        mask = np.zeros(img.shape, np.uint8)
        cv2.drawContours(mask, contours, i, 255, cv2.FILLED)
        mask = cv2.bitwise_and(img, mask)
        res = cv2.bitwise_or(res, mask)
        cv2.imshow('test', res)
        cv2.waitKey(0) 
Example #30
Source File: digital_display_ocr.py    From display_ocr with GNU General Public License v2.0 5 votes vote down vote up
def find_display_contour(edge_img_arr):
  display_contour = None
  edge_copy = edge_img_arr.copy()
  contours,hierarchy = cv2.findContours(edge_copy, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  top_cntrs = sorted(contours, key = cv2.contourArea, reverse = True)[:10]

  for cntr in top_cntrs:
    peri = cv2.arcLength(cntr,True)
    approx = cv2.approxPolyDP(cntr, 0.02 * peri, True)

    if len(approx) == 4:
      display_contour = approx
      break

  return display_contour