Python cv2扩展问题

时间:2017-12-16 06:20:55

标签: python opencv

我正在尝试制作一个omr扫描程序并关注this tutorial。 但是,我正在缩放图像,因为扫描图像的尺寸更大。在缩放图像和应用必要的滤镜时,我无法找到轮廓。当我应用four-point-perspective方法时,只显示一小部分。我仍然是OpenCV的新手,很难找到原因。

from imutils.perspective import four_point_transform
from imutils import contours
import numpy as np
import argparse
import imutils
import cv2

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
    help="path to the input image")
args = vars(ap.parse_args())

# define the answer key which maps the question number
# to the correct answer
ANSWER_KEY = {0: 1, 1: 4, 2: 0, 3: 3, 4: 1, 5: 1, 6: 4, 7: 0, 8: 3, 9: 1, 10: 1, 11: 4, 12: 0, 13: 3, 14: 1}

# load the image, convert it to grayscale, blur it
# slightly, then find edges
image = cv2.imread(args["image"])

r = 500.0 / image.shape[1]
dim = (500, int(image.shape[0] * r))

# perform the actual resizing of the image and show it
image_scaled = cv2.resize(image, dim, interpolation = cv2.INTER_AREA)

# cv2.imshow('edged', image)
# cv2.waitKey(0)

gray = cv2.cvtColor(image_scaled, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(blurred, 75, 200)

cv2.imshow('edged', edged)
cv2.waitKey(0)
# find contours in the edge map, then initialize
# the contour that corresponds to the document
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,
    cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
docCnt = None

# ensure that at least one contour was found
if len(cnts) > 0:
    # sort the contours according to their size in
    # descending order
    cnts = sorted(cnts, key=cv2.contourArea, reverse=True)

    # loop over the sorted contours
    for c in cnts:
        # approximate the contour
        peri = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.02 * peri, True)

        # if our approximated contour has four points,
        # then we can assume we have found the paper
        if len(approx) == 4:
            docCnt = approx
            break

# apply a four point perspective transform to both the
# original image and grayscale image to obtain a top-down
# birds eye view of the paper
paper = four_point_transform(image, docCnt.reshape(4, 2))
warped = four_point_transform(gray, docCnt.reshape(4, 2))

# apply Otsu's thresholding method to binarize the warped
# piece of paper
thresh = cv2.threshold(warped, 0, 255,
    cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]

cv2.imshow('edged', paper)
cv2.waitKey(0)

0 个答案:

没有答案