joyeecheung / perspective-correction

Automatic perspective correction on photos of A4 papers using Canny detector and Hough transform with opencv-python.
35 stars 16 forks source link

Some problems in handling the abnormal situations on finding hough lines #1

Open a20185 opened 7 years ago

a20185 commented 7 years ago

First of all , thanks for sharing your code for the A4-correlation.

However , when I try to generate some outputs using your code , it will raise python TypeError, saying that

TypeError: 'NoneType' object has no attribute 'getitem'

After finding and locating the problems , I found that the reason of this problem is because of the python interface cv2.HoughLines(edges, rho, theta, threshold) method provided by the standard OpenCV Library will return None if none of the Hough edges was found in the given image by the certain threshold value. Therefore , in the following method in src/perspective.py , L152~L226:

correct_perspective(img, threshold_max, threshold_min, median_blur_size, rho, theta, threshold_intersect, threshold_distance, perpendicular_margin, intermediate)

Should provide Exception Handler to check for TypeError by using try...except block to wrap the following code:

  lines = cv2.HoughLines(edges, rho, theta, threshold_intersect)
  lines = filter_perpendicular(lines[0], perpendicular_margin)
  lines = eliminate_duplicates(img, lines, threshold_distance)

or simply using if-else to handle the exceptions like:

lines = cv2.HoughLines(edges, rho, theta, threshold_intersect)
    if lines is not None:
      lines = filter_perpendicular(lines[0], perpendicular_margin)
      lines = eliminate_duplicates(img, lines, threshold_distance)
    else:
      lines = []

will works fine.

a20185 commented 7 years ago

Moreover , in case to the loop in the same function

 while (len(lines) < 4):
     ...

will also be better be improved by adding the loop condition of restricting the threshold_intersect variable to more than zero to handle the abnormal situations.