How to use the imutils.contours function in imutils

To help you get started, we’ve selected a few imutils examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github apollos / opencv-practice / SB_Code / chapter21-breaking_captchas / test_model.py View on Github external
image = cv2.imread(imagePath)
	gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
	gray = cv2.copyMakeBorder(gray, 20, 20, 20, 20,
		cv2.BORDER_REPLICATE)

	# threshold the image to reveal the digits
	thresh = cv2.threshold(gray, 0, 255,
		cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]

	# find contours in the image, keeping only the four largest ones,
	# then sort them from left-to-right
	cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
		cv2.CHAIN_APPROX_SIMPLE)
	cnts = imutils.grab_contours(cnts)
	cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:4]
	cnts = contours.sort_contours(cnts)[0]

	# initialize the output image as a "grayscale" image with 3
	# channels along with the output predictions
	output = cv2.merge([gray] * 3)
	predictions = []

	# loop over the contours
	for c in cnts:
		# compute the bounding box for the contour then extract the
		# digit
		(x, y, w, h) = cv2.boundingRect(c)
		roi = gray[y - 5:y + h + 5, x - 5:x + w + 5]

		# pre-process the ROI and classify it then classify it
		roi = preprocess(roi, 28, 28)
		roi = np.expand_dims(img_to_array(roi), axis=0) / 255.0
github EvilPort2 / final-year-project / modules / gesture_recognition / gesture_action.py View on Github external
cv2.imshow("Thresh", thresh)

		cnts = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[1]
		cnts = contour_area_sort(cnts, 350)

		print(count_stop_left, count_stop_right, count_stop)
		# 2 hand gesture
		if len(cnts) == 2:
			if flags == [True, False, False]:
				flags = [False, False, True]
				continue
			flag_do_gesture = 0
			line_pts = deque(maxlen = buff)

			cnt = cnts[:2]														  # take the top 2 contours
			cnt = contours.sort_contours(cnt, method = "left-to-right")[0]		  # sort the contours from left to right

			contour_left = cnt[0]
			contour_right = cnt[1]

			rect_left = cv2.minAreaRect(contour_left)
			center_left = list(rect_left[0])
			box = cv2.boxPoints(rect_left)
			box = np.int0(box)
			cv2.circle(img, tuple(np.int0(center_left)), 2, (0, 255, 0), 2)
			cv2.drawContours(img,[box],0,(0,0,255),2)
			line_pts1.appendleft(tuple(np.int0(center_left)))

			rect_right = cv2.minAreaRect(contour_right)
			center_right = list(rect_right[0])
			box = cv2.boxPoints(rect_right)
			box = np.int0(box)
github jrosebr1 / imutils / demos / sorting_contours.py View on Github external
# load the shapes image clone it, convert it to grayscale, and
# detect edges in the image
image = cv2.imread("../demo_images/shapes.png")
orig = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
edged = imutils.auto_canny(gray)

# find contours in the edge map
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,
	cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

# loop over the (unsorted) contours and label them
for (i, c) in enumerate(cnts):
	orig = contours.label_contour(orig, c, i, color=(240, 0, 159))

# show the original image
cv2.imshow("Original", orig)

# loop over the sorting methods
for method in ("left-to-right", "right-to-left", "top-to-bottom", "bottom-to-top"):
	# sort the contours
	(cnts, boundingBoxes) = contours.sort_contours(cnts, method=method)
	clone = image.copy()

	# loop over the sorted contours and label them
	for (i, c) in enumerate(cnts):
		sortedImage = contours.label_contour(clone, c, i, color=(240, 0, 159))

	# show the sorted contour image
	cv2.imshow(method, sortedImage)
github qindongliang / answer_sheet_scan / sheet_scan_example01.py View on Github external
questionCnts = []
        for cxx in r_cnt:
            # 通过矩形,标记每一个指定的轮廓
            x, y, w, h = cv.boundingRect(cxx)
            ar = w / float(h)


            if w >= 20 and h >= 20 and ar >= 0.9 and ar <= 1.1:
                # 使用红色标记,满足指定条件的图形
                # cv.rectangle(ox_sheet, (x, y), (x + w, y + h), (0, 0, 255), 2)
                # 把每个选项,保存下来
                questionCnts.append(cxx)

        cv.imshow("ox_1", ox_sheet)
        # 按坐标从上到下排序
        questionCnts = contours.sort_contours(questionCnts, method="top-to-bottom")[0]

        # 使用np函数,按5个元素,生成一个集合
        for (q, i) in enumerate(np.arange(0, len(questionCnts), 5)):

            # 获取按从左到右的排序后的5个元素
            cnts = contours.sort_contours(questionCnts[i:i + 5])[0]

            bubble_rows=[]

            # 遍历每一个选项
            for (j, c) in enumerate(cnts):

                # 生成一个大小与透视图一样的全黑背景图布
                mask = np.zeros(tx_sheet.shape, dtype="uint8")
                # 将指定的轮廓+白色的填充写到画板上,255代表亮度值,亮度=255的时候,颜色是白色,等于0的时候是黑色
                cv.drawContours(mask, [c], -1, 255, -1)
github bthicks / OMR-Grader / fifty_questions.py View on Github external
answerContours.append(contour)
            yValues.append(y)
            height = h

      minY = yValues[len(yValues) - 1] - int(height * 0.1)
      maxY = yValues[0] + height + int(height * 0.25)

      # grade bubbles in question box
      answerContours, _ = cutils.sort_contours(answerContours, method="left-to-right")
      length = len(answerContours)
      mid = int(len(answerContours) / 2)
      column1 = answerContours[0 : mid]
      column2 = answerContours[mid : length]

      # grade questions 1-25
      column1, _ = cutils.sort_contours(column1, method="top-to-bottom")
      self.gradeAnswersColumn(column1, 0, answersContour, minY, maxY)

      # grade questions 26-50
      column2, _ = cutils.sort_contours(column2, method="top-to-bottom")
      self.gradeAnswersColumn(column2, 1, answersContour, minY, maxY)
github OlivierLD / raspberry-coffee / JupyterNotebooks / deep.learning.crash.course / digit.demo / sample.05.22.py View on Github external
# compute the bounding box of the contour
        (x, y, w, h) = cv2.boundingRect(c)
        print("Found Contours x:{} y:{} w:{} h:{} ({})".format(x, y, w, h,
                                                               CONTOUR_COLORS[contour_index % len(CONTOUR_COLORS)]['name']))
        # if the contour is sufficiently large, it must be a digit
        min_height = int(image.shape[0] * 0.6)
        print("Original {}x{}, Min Height: {}".format(image.shape[1], image.shape[0], min_height))
        if w >= 15 and h >= min_height:  # <= That's the tricky part
            print("\tAdding Contours x:{} y:{} w:{} h:{}".format(x, y, w, h))
            digit_contours.append(c)
        contour_index += 1

    print("Retained {}".format(len(digit_contours)))
    # sort the contours from left-to-right, then initialize the
    # actual digits themselves
    digit_contours = contours.sort_contours(digit_contours,
                                            method="left-to-right")[0]
    # loop over each of the digits
    idx = 0
    padding = int(image.shape[0] * 0.05)
    for c in digit_contours:
        idx += 1
        # extract the digit ROI
        (x, y, w, h) = cv2.boundingRect(c)
        #
        # roi = saved_image[y:y + h, x:x + w]  # <= THIS is the image that will be processed (recognized) later on.
        top = y - padding
        bottom = y + h + padding
        left = x - padding
        right = x + w + padding
        roi = saved_image[top:bottom, left:right]  # <= THIS is the image that will be processed (recognized) later on.
        # Paste this image into a bigger, white and square one
github inuyasha2012 / answer-sheet-scan / sheet.py View on Github external
for i in range(len(question_cnts)):
        cv2.drawContours(temp2_ans_img, question_cnts, i, (0, 0, 0), 1)

    # cv2.imshow('temp', temp2_ans_img)
    # cv2.waitKey(0)

    # 如果轮廓小于特定值,重新扫描
    # TODO 运用统计分析排除垃圾轮廓
    # if len(question_cnts) != CHOICE_CNT_COUNT:
    #     raise ContourCountError

    # cv2.imshow('temp', temp_ans_img)
    # cv2.waitKey(0)

    # 对轮廓之上而下的排序
    question_cnts, cnts_pos = contours.sort_contours(question_cnts, method="top-to-bottom")
    rows = sort_by_row(list(cnts_pos))
    cols = sort_by_col(list(cnts_pos))

    # cv2.imshow('temp', temp2_ans_img)
    # cv2.waitKey(0)

    insert_null_2_rows(cols, rows)
    # 获得答案
    rows, res = get_ans(ans_img, rows)
    if not res[0]:
        print res[1]
        cv2.imshow('temp1', temp2_ans_img)
        cv2.waitKey(0)
        print 'end'
    else:
        print res
github jrosebr1 / imutils / demos / sorting_contours.py View on Github external
# find contours in the edge map
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,
	cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

# loop over the (unsorted) contours and label them
for (i, c) in enumerate(cnts):
	orig = contours.label_contour(orig, c, i, color=(240, 0, 159))

# show the original image
cv2.imshow("Original", orig)

# loop over the sorting methods
for method in ("left-to-right", "right-to-left", "top-to-bottom", "bottom-to-top"):
	# sort the contours
	(cnts, boundingBoxes) = contours.sort_contours(cnts, method=method)
	clone = image.copy()

	# loop over the sorted contours and label them
	for (i, c) in enumerate(cnts):
		sortedImage = contours.label_contour(clone, c, i, color=(240, 0, 159))

	# show the sorted contour image
	cv2.imshow(method, sortedImage)

# wait for a keypress
cv2.waitKey(0)
github bthicks / OMR-Grader / short_answer.py View on Github external
# Split bubbles by question.
        questions = [[] for i in range(self.config['answer_rows'])]

        for bubble in column:
            (x, y, w, h) = cv.boundingRect(bubble)
            y += self.config['answer_y']

            if (y >= self.config['answer_y_min'] - self.config['y_error'] and
                y <= self.config['answer_y_min'] + self.config['y_error']):
                questions[0].append(bubble)
            if (y >= self.config['answer_y_max'] - self.config['y_error'] and
                y <= self.config['answer_y_max'] + self.config['y_error']):
                questions[1].append(bubble)

        for (i, question) in enumerate(questions):
            question, _ = cutils.sort_contours(question, method="left-to-right")
            bubbled = ''
            bounding_rects = []

            # Calculate x and y boundaries of this question for image slicing.
            for bubble in question:
                bounding_rects.append(cv.boundingRect(bubble))

            y_min = min(bounding_rects, key=lambda x: x[1])[1] + self.config['answer_y']
            y_max = max(bounding_rects, key=lambda x: x[1])[1] + self.config['answer_y']

            if (column_num == 0):
                x_min = self.config['answer_x_min_1']
                x_max = self.config['answer_x_max_1']
            elif (column_num == 1):
                x_min = self.config['answer_x_min_2']
                x_max = self.config['answer_x_max_2']
github OlivierLD / raspberry-coffee / opencv / src / main / python / pyimagesearch / recognize-digits / recognize_digits.py View on Github external
cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
digitCnts = []

# loop over the digit area candidates
for c in cnts:
    # compute the bounding box of the contour
    (x, y, w, h) = cv2.boundingRect(c)

    # if the contour is sufficiently large, it must be a digit
    if w >= 15 and 30 <= h <= 40:
        digitCnts.append(c)

# sort the contours from left-to-right, then initialize the
# actual digits themselves
digitCnts = contours.sort_contours(digitCnts,
                                   method="left-to-right")[0]
digits = []

# loop over each of the digits
idx = 0
for c in digitCnts:
    idx += 1
    # extract the digit ROI
    (x, y, w, h) = cv2.boundingRect(c)
    roi = thresh[y:y + h, x:x + w]
    cv2.imshow("Edged-{}".format(idx), roi)
    # compute the width and height of each of the 7 segments
    # we are going to examine
    (roiH, roiW) = roi.shape
    (dW, dH) = (int(roiW * 0.25), int(roiH * 0.15))
    dHC = int(roiH * 0.05)

imutils

A series of convenience functions to make basic image processing functions such as translation, rotation, resizing, skeletonization, displaying Matplotlib images, sorting contours, detecting edges, and much more easier with OpenCV and both Python 2.7 and Python 3.

MIT
Latest version published 4 years ago

Package Health Score

64 / 100
Full package analysis