NameError: имя 'screenCnt' не определено - PullRequest
0 голосов
/ 31 марта 2020
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 и ноль выдавать ту же ошибку. Пожалуйста, помогите мне с ошибкой. Тем не менее иногда это работает. один раз в 50 попыток.

или если я установил screenCnt = 0 или screenCnt = None, это дает ошибку

error Traceback (последний последний вызов) в 123 # показывает контур (контур) ) листа бумаги 124 #print («ШАГ 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: утверждение не выполнено) npoints> 0 в функции 'cv :: drawContours'

1 Ответ

0 голосов
/ 31 марта 2020

Ваша переменная screenCnt основана на операторе if. Если оператор if не соответствует действительности, не будет определено.

   if len(approx) == 4:
    screenCnt = approx
    break
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...