|
2 | 2 | import argparse
|
3 | 3 | import cv2
|
4 | 4 |
|
5 |
| -# construct the argument parse and parse the arguments |
| 5 | + |
6 | 6 | ap = argparse.ArgumentParser()
|
7 | 7 | ap.add_argument("-i", "--image", required=True, help="path to input image file")
|
8 | 8 | args = vars(ap.parse_args())
|
9 | 9 |
|
10 |
| -# load the image from disk |
11 | 10 | image = cv2.imread(args["image"])
|
12 | 11 |
|
13 |
| -# convert the image to grayscale and flip the foreground |
14 |
| -# and background to ensure foreground is now "white" and |
15 |
| -# the background is "black" |
16 | 12 | gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
17 | 13 | gray = cv2.bitwise_not(gray)
|
18 | 14 |
|
19 |
| -# threshold the image, setting all foreground pixels to |
20 |
| -# 255 and all background pixels to 0 |
21 | 15 | thresh = cv2.threshold(gray, 0, 255,
|
22 | 16 | cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
|
23 | 17 |
|
24 |
| -# grab the (x, y) coordinates of all pixel values that |
25 |
| -# are greater than zero, then use these coordinates to |
26 |
| -# compute a rotated bounding box that contains all |
27 |
| -# coordinates |
28 | 18 | coords = np.column_stack(np.where(thresh > 0))
|
29 | 19 | angle = cv2.minAreaRect(coords)[-1]
|
30 | 20 |
|
31 |
| -# the `cv2.minAreaRect` function returns values in the |
| 21 | + |
32 | 22 | # range [-90, 0); as the rectangle rotates clockwise the
|
33 | 23 | # returned angle trends to 0 -- in this special case we
|
34 | 24 | # need to add 90 degrees to the angle
|
35 | 25 | if angle < -45:
|
36 | 26 | angle = -(90 + angle)
|
37 | 27 |
|
38 |
| -# otherwise, just take the inverse of the angle to make |
39 |
| -# it positive |
40 | 28 | else:
|
41 | 29 | angle = -angle
|
42 | 30 |
|
43 |
| -# rotate the image to deskew it |
44 | 31 | (h, w) = image.shape[:2]
|
45 | 32 | center = (w // 2, h // 2)
|
46 | 33 | M = cv2.getRotationMatrix2D(center, angle, 1.0)
|
47 | 34 | rotated = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
|
48 | 35 |
|
49 |
| -# draw the correction angle on the image so we can validate it |
50 | 36 | cv2.putText(rotated, "Angle: {:.2f} degrees".format(angle),(10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
|
51 |
| - |
52 |
| -# show the output image |
53 | 37 | print("[INFO] angle: {:.3f}".format(angle))
|
54 | 38 | cv2.imshow("Input", image)
|
55 | 39 | cv2.imshow("Rotated", rotated)
|
|
0 commit comments