NameError: name 'screenCnt' is not defined

Question:

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:EnvOGImages*.*"
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:EnvCropImagescrop{}.png'.format(bb),warped)
cv2.waitKey(1000)
cv2.destroyAllWindows()

Error is

---------------------------------------------------------------------------
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

This code was run a hundred times before the same as it is but suddenly starts giving this error. No IndentationError. Tried screenCnt = 0 and null giving the same error. Please help me out with the error. Still, sometimes it works. once in 50 tries.

or if i set screenCnt = 0 or screenCnt = None it giving error

error Traceback (most recent call last) in 123 # show the contour (outline) of the piece of paper 124 #print(“STEP 2: Find contours of paper”) –> 125 cv2.drawContours(orig, [screenCnt], -1, (0, 255, 0), 2) 126 127 # apply the four point transform to obtain a top-down

error: OpenCV(4.2.0) C:projectsopencv-pythonopencvmodulesimgprocsrcdrawing.cpp:2509: error: (-215:Assertion failed) npoints > 0 in function ‘cv::drawContours’

Asked By: B.H. Burhani

||

Answers:

Your variable screenCnt is based off of an if statement. If the if statement isn’t true, it won’t be defined.

   if len(approx) == 4:
    screenCnt = approx
    break
Answered By: exe

your if statement is not true so it is giving this error
so you can try this,

approx = cv2.approxPolyDP(c, 0.10 * peri, True)

if the problem continues then you can try keep changing the values which is multyplying by the peri and try to chek whether it is right or not.
In my case it works.

Answered By: kishan Kumar