Python cv2.RETR_LIST Examples

The following are 30 code examples of cv2.RETR_LIST(). 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: 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 #2
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 #3
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 #4
Source File: annotation.py    From imantics with MIT License 6 votes vote down vote up
def polygons(self):
        """
        Returns or generates :class:`Polygons` representation of mask.

        :returns: Polygons representation
        :rtype: :class:`Polygons`
        """
        if not self._c_polygons:

            # Generate polygons from mask
            mask = self.array.astype(np.uint8)
            mask = cv2.copyMakeBorder(mask, 1, 1, 1, 1, cv2.BORDER_CONSTANT, value=0)
            polygons = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE, offset=(-1, -1))
            polygons = polygons[0] if len(polygons) == 2 else polygons[1]
            polygons = [polygon.flatten() for polygon in polygons]

            self._c_polygons = Polygons(polygons)
            self._c_polygons._c_mask = self

        return self._c_polygons 
Example #5
Source File: DetectChars.py    From ALPR-Indonesia with MIT License 6 votes vote down vote up
def findPossibleCharsInPlate(imgGrayscale, imgThresh):
    listOfPossibleChars = []                        # this will be the return value
    contours = []
    imgThreshCopy = imgThresh.copy()

            # find all contours in plate
    contours, npaHierarchy = cv2.findContours(imgThreshCopy, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

    for contour in contours:                        # for each contour
        possibleChar = PossibleChar.PossibleChar(contour)

        if checkIfPossibleChar(possibleChar):              # if contour is a possible char, note this does not compare to other chars (yet) . . .
            listOfPossibleChars.append(possibleChar)       # add to list of possible chars
        # end if
    # end if

    return listOfPossibleChars
# end function

################################################################################################### 
Example #6
Source File: read_human36m.py    From human_dynamics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def crop_and_clean_mask_to_int(mask, x, y, w, h):
    mask = np.uint8(mask[y:y + h, x:x + w]) * 255

    # TODO: put this into a function (it's used above as well)
    cnts, hier = cv2.findContours(mask.copy(), cv2.RETR_LIST,
                                  cv2.CHAIN_APPROX_SIMPLE)

    max_id = 0
    max_length = len(cnts[0])
    for i in range(1, len(cnts)):
        if len(cnts[i]) > max_length:
            max_id = i
            max_length = len(cnts[i])

    tmp_mask = np.dstack((mask, mask, mask))
    for i, cnt in enumerate(cnts):
        if i != max_id:
            cv2.drawContours(tmp_mask, [cnt], 0, (0, 0, 0), -1)
    return cv2.split(tmp_mask)[0] 
Example #7
Source File: read_human36m.py    From human_dynamics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def crop_image(silhs):
    res = np.asarray(silhs).any(axis=0)
    cnts, hier = cv2.findContours(
        np.uint8(res) * 255, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    """
    checks = []
    for cnt in cnts:
        kk = np.zeros((1000, 1000, 3), dtype=np.uint8)
        hull = cv2.convexHull(cnt)
        cv2.drawContours(kk, [cnt], 0, (255,255,255), -1)
        checks.append(kk)
    """

    max_id = 0
    max_length = len(cnts[0])
    for i in range(1, len(cnts)):
        if len(cnts[i]) > max_length:
            max_id = i
            max_length = len(cnts[i])

    (x, y, w, h) = cv2.boundingRect(cnts[max_id])
    return (x, y, w, h) 
Example #8
Source File: squares.py    From PyCV-time with MIT License 5 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)
            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 #9
Source File: convexity_defects_smoothen.py    From OpenCV-3-x-with-Python-By-Example with MIT License 5 votes vote down vote up
def get_all_contours(img): 
    ref_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
    ret, thresh = cv2.threshold(ref_gray, 127, 255, 0)
    im2, contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE )
    return contours 
Example #10
Source File: TableRecognition.py    From OTR with GNU General Public License v3.0 5 votes vote down vote up
def compute_missing_cell_contours(self, missing_cells_mask):
        contx, _ = _find_contours(missing_cells_mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_TC89_KCOS)
        return contx 
Example #11
Source File: seg_detector_representer.py    From DBNet.pytorch with Apache License 2.0 5 votes vote down vote up
def boxes_from_bitmap(self, pred, _bitmap, dest_width, dest_height):
        '''
        _bitmap: single map with shape (H, W),
            whose values are binarized as {0, 1}
        '''

        assert len(_bitmap.shape) == 2
        bitmap = _bitmap.cpu().numpy()  # The first channel
        pred = pred.cpu().detach().numpy()
        height, width = bitmap.shape
        contours, _ = cv2.findContours((bitmap * 255).astype(np.uint8), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
        num_contours = min(len(contours), self.max_candidates)
        boxes = np.zeros((num_contours, 4, 2), dtype=np.int16)
        scores = np.zeros((num_contours,), dtype=np.float32)

        for index in range(num_contours):
            contour = contours[index].squeeze(1)
            points, sside = self.get_mini_boxes(contour)
            if sside < self.min_size:
                continue
            points = np.array(points)
            score = self.box_score_fast(pred, contour)
            if self.box_thresh > score:
                continue

            box = self.unclip(points, unclip_ratio=self.unclip_ratio).reshape(-1, 1, 2)
            box, sside = self.get_mini_boxes(box)
            if sside < self.min_size + 2:
                continue
            box = np.array(box)
            if not isinstance(dest_width, int):
                dest_width = dest_width.item()
                dest_height = dest_height.item()

            box[:, 0] = np.clip(np.round(box[:, 0] / width * dest_width), 0, dest_width)
            box[:, 1] = np.clip(np.round(box[:, 1] / height * dest_height), 0, dest_height)
            boxes[index, :, :] = box.astype(np.int16)
            scores[index] = score
        return boxes, scores 
Example #12
Source File: distance_to_camera.py    From Hand-Detection-and-Distance-Estimation with MIT License 5 votes vote down vote up
def find_marker(image):
    # convert the image to grayscale, blur it, and detect edges
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (5, 5), 0)
    edged = cv2.Canny(gray, 35, 125)

    # find the contours in the edged image and keep the largest one;
    # we'll assume that this is our piece of paper in the image
    cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if imutils.is_cv2() else cnts[1]
    c = max(cnts, key = cv2.contourArea)

    # compute the bounding box of the of the paper region and return it
    return cv2.minAreaRect(c) 
Example #13
Source File: toolbox_opencv.py    From remi with Apache License 2.0 5 votes vote down vote up
def __init__(self, retrieval_mode=cv2.RETR_LIST, approximation_method=cv2.CHAIN_APPROX_SIMPLE, *args, **kwargs):
        self.__retrieval_mode = retrieval_mode
        self.__approximation_method = approximation_method
        self.__min_arc_length = 0
        self.__max_arc_length = 9223372036854775807
        self.__min_contour_area = 0
        self.__max_contour_area = 9223372036854775807
        self.__discard_convex = False
        self.__discard_non_convex = False
        self.__min_roundness = 0.0
        self.__max_roundness = 1.0
        super(OpencvFindContours, self).__init__("", *args, **kwargs)
        self.on_new_contours_result.do = self.do_contours_result 
Example #14
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 #15
Source File: WordSegmentation.py    From WordSegmentation with MIT License 5 votes vote down vote up
def wordSegmentation(img, kernelSize=25, sigma=11, theta=7, minArea=0):
	"""Scale space technique for word segmentation proposed by R. Manmatha: http://ciir.cs.umass.edu/pubfiles/mm-27.pdf
	
	Args:
		img: grayscale uint8 image of the text-line to be segmented.
		kernelSize: size of filter kernel, must be an odd integer.
		sigma: standard deviation of Gaussian function used for filter kernel.
		theta: approximated width/height ratio of words, filter function is distorted by this factor.
		minArea: ignore word candidates smaller than specified area.
		
	Returns:
		List of tuples. Each tuple contains the bounding box and the image of the segmented word.
	"""

	# apply filter kernel
	kernel = createKernel(kernelSize, sigma, theta)
	imgFiltered = cv2.filter2D(img, -1, kernel, borderType=cv2.BORDER_REPLICATE).astype(np.uint8)
	(_, imgThres) = cv2.threshold(imgFiltered, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
	imgThres = 255 - imgThres

	# find connected components. OpenCV: return type differs between OpenCV2 and 3
	if cv2.__version__.startswith('3.'):
		(_, components, _) = cv2.findContours(imgThres, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
	else:
		(components, _) = cv2.findContours(imgThres, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

	# append components to result
	res = []
	for c in components:
		# skip small word candidates
		if cv2.contourArea(c) < minArea:
			continue
		# append bounding box and image of word to result list
		currBox = cv2.boundingRect(c) # returns (x, y, w, h)
		(x, y, w, h) = currBox
		currImg = img[y:y+h, x:x+w]
		res.append((currBox, currImg))

	# return list of words, sorted by x-coordinate
	return sorted(res, key=lambda entry:entry[0][0]) 
Example #16
Source File: segmenation.py    From mlcomp with Apache License 2.0 5 votes vote down vote up
def plot_mask(self, img: np.array, mask: np.array):
        if len(img.shape) == 2:
            img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
        img = img.astype(np.uint8)
        mask = mask.astype(np.uint8)

        for i, c in enumerate(mask):
            contours, _ = cv2.findContours(
                c, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE
            )
            color = self.colors[i] if self.colors else (0, 255, 0)
            for i in range(0, len(contours)):
                cv2.polylines(img, contours[i], True, color, 2)

        return img 
Example #17
Source File: cv_functions.py    From R-CNN_LIGHT with MIT License 5 votes vote down vote up
def contouring(binary_img=None):

    # return two values: contours, hierarchy
    # cv2.RETR_EXTERNAL

    return cv2.findContours(binary_img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) 
Example #18
Source File: geometry.py    From Cytomine-python-client with Apache License 2.0 5 votes vote down vote up
def find_components_list(self):
        return self._find_components(cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) 
Example #19
Source File: card.py    From idmatch with MIT License 5 votes vote down vote up
def remove_borders(image):
    image = cv2.imread(image)
    orig = image.copy()
    ratio = image.shape[0] / 500.0
    image = resize(image, height=500)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray,(7,7),0)
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
    contrasted = clahe.apply(blur)
    im = Image.fromarray(contrasted)
    
    edged = cv2.Canny(blur, 20, 170)
    _, cnts, _ = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
    largest_area = 0
    for c in cnts:
        r = cv2.minAreaRect(c)
        area = r[1][0]*r[1][1]
        if area > largest_area:
            largest_area = area
            rect = r

    screenCnt = np.int0(cv2.boxPoints(rect))
    im = Image.fromarray(edged)

    cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)
    im = Image.fromarray(image)

    if screenCnt is not None and len(screenCnt) > 0:
        return four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)
    return orig 
Example #20
Source File: censor_shapes.py    From OpenCV-3-x-with-Python-By-Example with MIT License 5 votes vote down vote up
def get_all_contours(img): 
    ref_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
    ret, thresh = cv2.threshold(ref_gray, 127, 255, 0)
    im2, contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE )
    return contours 
Example #21
Source File: smoothen contour_polygon.py    From OpenCV-3-x-with-Python-By-Example with MIT License 5 votes vote down vote up
def get_all_contours(img): 
    ref_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
    ret, thresh = cv2.threshold(ref_gray, 127, 255, 0)
    im2, contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE )
    return contours 
Example #22
Source File: best_contour_matching.py    From OpenCV-3-x-with-Python-By-Example with MIT License 5 votes vote down vote up
def get_all_contours(img): 
    ref_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
    ret, thresh = cv2.threshold(ref_gray, 127, 255, 0) 
    # Find all the contours in the thresholded image. The values 
    # for the second and third parameters are restricted to a 
    # certain number of possible values. You can learn more 'findContours' function here: 
    # http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html#findcontours
    im2, contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE )
    return contours

# Extract reference contour from the image 
Example #23
Source File: convexity_defects.py    From OpenCV-3-x-with-Python-By-Example with MIT License 5 votes vote down vote up
def get_all_contours(img): 
    ref_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
    ret, thresh = cv2.threshold(ref_gray, 127, 255, 0)
    im2, contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE )
    return contours 
Example #24
Source File: red_blob_detection.py    From visual-followme with GNU General Public License v3.0 5 votes vote down vote up
def detect_biggest_polygon(binary_img):
    binary_img_to_process = binary_img.copy()  # contour detection will mess up the image
    contours, _ = cv2.findContours(binary_img_to_process, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    biggest_contour = None
    if contours != []:
        biggest_contour_index = 0
        for i in range(1, len(contours)):
            if cv2.contourArea(contours[i]) > cv2.contourArea(contours[biggest_contour_index]):
                biggest_contour_index = i
        
        biggest_contour = contours[biggest_contour_index]
    return biggest_contour 
Example #25
Source File: image_functions.py    From niryo_one_ros with GNU General Public License v3.0 5 votes vote down vote up
def biggest_contours_finder(img, nb_contours_max=3):
    """
    Fonction to find the biggest contour in an binary image
    :param img: Binary Image
    :param nb_contours_max: maximal number of contours which will be returned
    :return: biggest contours found
    """
    contours = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)[-2]
    if not contours:
        return None
    contours_area = list()
    for cnt in contours:
        contours_area.append(cv2.contourArea(cnt))
    biggest_contours = []
    le = len(contours_area)
    if nb_contours_max > le:
        nb_contours = le
        id_contours_sorted_init = list(range(nb_contours))
    else:
        nb_contours = nb_contours_max
        id_contours_sorted_init = np.argpartition(contours_area, -nb_contours)[-nb_contours:]
    id_contours_sorted = [x for x in sorted(id_contours_sorted_init, key=lambda idi: -contours_area[idi])]

    for i in range(nb_contours):
        id_used = id_contours_sorted[i]

        if contours_area[id_used] < 400:
            break

        biggest_contours.append(contours[id_used])
    return biggest_contours 
Example #26
Source File: markers_detection.py    From niryo_one_ros with GNU General Public License v3.0 5 votes vote down vote up
def find_markers_from_img_thresh(img_thresh, max_dist_between_centers=3, min_radius_circle=4,
                                 max_radius_circle=35, min_radius_marker=7):
    contours = cv2.findContours(img_thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2]
    list_potential_markers = []
    for cnt in contours:
        (x, y), radius = cv2.minEnclosingCircle(cnt)
        if not min_radius_circle < radius < max_radius_circle:
            continue
        center = (int(round(x)), int(round(y)))
        radius = int(radius)
        list_potential_markers.append(PotentialMarker(center, radius, cnt))

    list_potential_markers = sorted(list_potential_markers, key=lambda m: m.x)
    list_good_candidates = []

    for i, potential_marker in enumerate(list_potential_markers):
        if potential_marker.is_merged:
            continue
        marker1 = Marker(potential_marker)
        center_marker = marker1.get_center()

        for potential_marker2 in list_potential_markers[i + 1:]:
            if potential_marker.is_merged:
                continue
            center_potential = potential_marker2.get_center()
            if center_potential[0] - center_marker[0] > max_dist_between_centers:
                break
            dist = euclidean_dist_2_pts(center_marker, center_potential)
            if dist <= max_dist_between_centers:
                marker1.add_circle(potential_marker2)
                center_marker = marker1.get_center()

        if marker1.nb_circles() > 2 and marker1.radius >= min_radius_marker:
            list_good_candidates.append(marker1)
            marker1.get_id_from_slice(img_thresh)

    return list_good_candidates 
Example #27
Source File: document.py    From web-document-scanner with MIT License 5 votes vote down vote up
def detect_edge(self, image, enabled_transform = False):
        dst = None
        orig = image.copy()

        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        blurred = cv2.GaussianBlur(gray, (5, 5), 0)
        edged = cv2.Canny(blurred, 0, 20)
        _, contours, _ = cv2.findContours(edged, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)

        contours = sorted(contours, key=cv2.contourArea, reverse=True)

        for cnt in contours:
            epsilon = 0.051 * cv2.arcLength(cnt, True)
            approx = cv2.approxPolyDP(cnt, epsilon, True)

            if len(approx) == 4:
                target = approx
                cv2.drawContours(image, [target], -1, (0, 255, 0), 2)

                if enabled_transform:
                    approx = rect.rectify(target)
                    # pts2 = np.float32([[0,0],[800,0],[800,800],[0,800]])
                    # M = cv2.getPerspectiveTransform(approx,pts2)
                    # dst = cv2.warpPerspective(orig,M,(800,800))
                    dst = self.four_point_transform(orig, approx)
                break

        return image, dst 
Example #28
Source File: DetectPlates.py    From ALPR-Indonesia with MIT License 5 votes vote down vote up
def findPossibleCharsInScene(imgThresh):
    listOfPossibleChars = []                # this will be the return value

    intCountOfPossibleChars = 0

    imgThreshCopy = imgThresh.copy()

    contours, npaHierarchy = cv2.findContours(imgThreshCopy, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)   # find all contours
    height, width = imgThresh.shape
    imgContours = np.zeros((height, width, 3), np.uint8)

    for i in range(0, len(contours)):                       # for each contour

        possibleChar = PossibleChar.PossibleChar(contours[i])

        if DetectChars.checkIfPossibleChar(possibleChar):                   # if contour is a possible char, note this does not compare to other chars (yet) . . .
            intCountOfPossibleChars = intCountOfPossibleChars + 1           # increment count of possible chars
            listOfPossibleChars.append(possibleChar)                        # and add to list of possible chars
        # end if
    # end for

    return listOfPossibleChars
# end function


################################################################################################### 
Example #29
Source File: extract_lines.py    From hazymaze with Apache License 2.0 5 votes vote down vote up
def find_items(maze_image):
    # Preprocessing to find the contour of the shapes
    h, w = maze_image.shape[0], maze_image.shape[1]
    dim = (h+w)//2
    b_and_w = cv2.cvtColor(maze_image, cv2.COLOR_BGR2GRAY)
    edges = cv2.GaussianBlur(b_and_w, (11, 11), 0)
    edges = cv2.adaptiveThreshold(edges, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 9, 2)

    cv2.rectangle(edges,(0, 0),(w-1,h-1),(255,255,255),16)
    contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

    # cv2.imshow('d', edges)

    items = []

    if contours:
        item_mask = np.zeros(edges.shape, np.uint8)
        conts = sorted(contours, key=lambda x: cv2.contourArea(x), reverse=False)

        for cnt in conts:

            if cv2.contourArea(cnt) > 0.35*dim:
                return items, item_mask

            elif cv2.contourArea(cnt) > 0.05*dim:
                d = np.mean(cnt, axis=0)
                d[0][0], d[0][1] = int(round(d[0][0])), int(round(d[0][1]))

                # TODO adjust the size here?
                if cv2.contourArea(cnt) < 0.1*dim:
                    items.append((d, 'smol'))
                    cv2.drawContours(item_mask, [cnt], -1, (255,255,255), -1)
                else:
                    items.append((d, 'big'))
                    cv2.drawContours(item_mask, [cnt], -1, (255,255,255), -1)

    return items, item_mask 
Example #30
Source File: cut_part.py    From 2019-CCF-BDCI-OCR-MCZJ-OCR-IdentificationIDElement with MIT License 5 votes vote down vote up
def find_bbox(img, img_closed):  # 寻找身份证正反面区域
    """
    根据二值化结果判定并裁剪出身份证正反面区域
    :param img: 原始RGB图片
    :param img_closed: 二值化后的图片
    :return: 身份证正反面区域
    """
    (contours, _) = cv2.findContours(img_closed.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)  # 求出框的个数
    # 这里opencv如果版本不对(4.0或以上)会报错,只需把(contours, _)改成 (_, contours, _)

    contours = sorted(contours, key=cv2.contourArea, reverse=True)  # 按照面积大小排序

    countours_res = []
    for i in range(0, len(contours)):
        area = cv2.contourArea(contours[i])  # 计算面积

        if (area <= 0.4 * img.shape[0] * img.shape[1]) and (area >= 0.05 * img.shape[0] * img.shape[1]):
            # 人为设定,身份证正反面框的大小不会超过整张图片大小的0.4,不会小于0.05(这个参数随便设置的)
            rect = cv2.minAreaRect(contours[i])  # 最小外接矩,返回值有中心点坐标,矩形宽高,倾斜角度三个参数
            box = cv2.boxPoints(rect)
            left_down, right_down, left_up, right_up = point_judge([int(rect[0][0]), int(rect[0][1])], box)
            src = np.float32([left_down, right_down, left_up, right_up])  # 这里注意必须对应

            dst = np.float32([[0, 0], [int(max(rect[1][0], rect[1][1])), 0], [0, int(min(rect[1][0], rect[1][1]))],
                              [int(max(rect[1][0], rect[1][1])),
                               int(min(rect[1][0], rect[1][1]))]])  # rect中的宽高不清楚是个怎么机制,但是对于身份证,肯定是宽大于高,因此加个判定
            m = cv2.getPerspectiveTransform(src, dst)  # 得到投影变换矩阵
            result = cv2.warpPerspective(img, m, (int(max(rect[1][0], rect[1][1])), int(min(rect[1][0], rect[1][1]))),
                                         flags=cv2.INTER_CUBIC)  # 投影变换
            countours_res.append(result)
    return countours_res  # 返回身份证区域