NameError:未定义名称“ screenCnt”

时间:2020-03-31 05:55:39

标签: python python-3.x opencv jupyter-notebook anaconda

import numpy as np
import cv2
import re
import glob
import imutils
import argparse
from skimage.filters import threshold_local
from PIL import Image
import PIL.Image

def order_points(pts):
rect = np.zeros((4, 2), dtype = "float32")
s = pts.sum(axis = 1)
rect[0] = pts[np.argmin(s)]
rect[2] = pts[np.argmax(s)]
diff = np.diff(pts, axis = 1)
rect[1] = pts[np.argmin(diff)]
rect[3] = pts[np.argmax(diff)]

return rect
def four_point_transform(image, pts):

rect = order_points(pts)
(tl, tr, br, bl) = rect
widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))
maxWidth = max(int(widthA), int(widthB))
heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))
maxHeight = max(int(heightA), int(heightB))
dst = np.array([
    [0, 0],
    [maxWidth - 1, 0],
    [maxWidth - 1, maxHeight - 1],
    [0, maxHeight - 1]], dtype = "float32")

M = cv2.getPerspectiveTransform(rect, dst)
warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))
return warped
path = "E:\Env\OGImages\*.*"
for bb,img in enumerate(glob.glob(path)):

OG_img_1 = cv2.imread(img, cv2.IMREAD_COLOR)
kernel_sharpening = np.array([[-1,-1,-1,-1,-1],
                           [   -1, 2, 2, 2,-1],
                           [   -1, 2, 8, 2,-1],
                           [   -1, 2, 2, 2,-1],
                           [   -1,-1,-1,-1,-1]])/8.0
OG_img = cv2.filter2D(OG_img_1, -1, kernel_sharpening)
ratio = OG_img.shape[0] / 500.0
orig = OG_img.copy()
image = imutils.resize(OG_img, height = 500)

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

cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]

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

    # our approximated contour should have four points
    if len(approx) == 4:
        screenCnt = approx
        break

cv2.drawContours(orig, [screenCnt], -1, (0, 255, 0), 2)

warped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)
warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
cv2.imshow("output",orig)
cv2.imwrite('out/'+'Output Image.PNG', warped)
cv2.imwrite('E:\Env\CropImages\crop{}.png'.format(bb),warped)
cv2.waitKey(1000)
cv2.destroyAllWindows()

错误是

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-68713fc9d803> in <module>
121 # show the contour (outline) of the piece of paper
122 #print("STEP 2: Find contours of paper")
--> 123     cv2.drawContours(orig, [screenCnt], -1, (0, 255, 0), 2)
124 
125 #     apply the four point transform to obtain a top-down

NameError: name 'screenCnt' is not defined

此代码之前运行了一百次,但突然开始出现此错误。没有IndentationError。尝试screenCnt = 0,并且返回null则给出相同的错误。请帮我解决错误。 不过,有时候还是可以。每50次尝试一次。

或者如果我将screenCnt = 0或screenCnt = None设置为错误

123中的错误回溯(最近一次通话最后一次)#显示纸的轮廓(轮廓)124 #print(“ STEP 2:查找纸的轮廓”)-> 125 cv2.drawContours(orig,[ screenCnt],-1,(0,255,0),2)126 127#应用四点变换获得自顶向下

错误:OpenCV(4.2.0)C:\ projects \ opencv-python \ opencv \ modules \ imgproc \ src \ drawing.cpp:2509:错误:(-215:断言失败)函数'cv中的npoints> 0 :: drawContours'

1 个答案:

答案 0 :(得分:0)

您的变量screenCnt基于 if语句。。如果if语句不正确,则将不定义它。

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