0
$\begingroup$

I wrote a script to take scanned images and crop out the background from them as well as rotate them to the proper orthogonal orientation (my set of images were not initially scanned properly and many are a few degrees off (see images below). It worked well for one image that I was testing the script with but not with other for which the borders are folded or damaged. Please help me find a way to define the corners of the image in a different way such that it will work with these old damaged pictures.

Based on this post the problem seems to be that the folded corners etc are causing the following error:

UnboundLocalError: local variable 'screenCnt' referenced before assignment

The code seems to fail somewhere in here (happy to share more of the code as well, I plan on open sourcing this anyway):

    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]
# loop over the 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 that we have found our screen
    if len(approx) == 4:
        screenCnt = approx
        break
# show the contour (outline) of the piece of paper
print("STEP 2: Find contours of paper")
cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)

The code processes this image perfectly

This image gets the error, it likely comes from the folded edge as well as the uneven bottom edge that seems to be ripped

$\endgroup$
2
  • $\begingroup$ The issue is that you are referencing the screenCnt variable, which only seems to be assigned a value in the case that len(approx) == 4. Therefore for all other cases the variable is not defined and the last line of code cannot be executed. $\endgroup$
    – Oxbowerce
    Commented Aug 16, 2022 at 11:41
  • $\begingroup$ I'm working on a similar project, you mentioned you planned to open source yours. If it's available, I'd love to take a look at it. $\endgroup$ Commented Oct 26, 2022 at 17:58

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.