Skip to content

Commit b92f5be

Browse files
authored
Orientation.py
1 parent 9b4c01e commit b92f5be

File tree

1 file changed

+2
-18
lines changed

1 file changed

+2
-18
lines changed

Orientation.py

+2-18
Original file line numberDiff line numberDiff line change
@@ -2,54 +2,38 @@
22
import argparse
33
import cv2
44

5-
# construct the argument parse and parse the arguments
5+
66
ap = argparse.ArgumentParser()
77
ap.add_argument("-i", "--image", required=True, help="path to input image file")
88
args = vars(ap.parse_args())
99

10-
# load the image from disk
1110
image = cv2.imread(args["image"])
1211

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"
1612
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
1713
gray = cv2.bitwise_not(gray)
1814

19-
# threshold the image, setting all foreground pixels to
20-
# 255 and all background pixels to 0
2115
thresh = cv2.threshold(gray, 0, 255,
2216
cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
2317

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
2818
coords = np.column_stack(np.where(thresh > 0))
2919
angle = cv2.minAreaRect(coords)[-1]
3020

31-
# the `cv2.minAreaRect` function returns values in the
21+
3222
# range [-90, 0); as the rectangle rotates clockwise the
3323
# returned angle trends to 0 -- in this special case we
3424
# need to add 90 degrees to the angle
3525
if angle < -45:
3626
angle = -(90 + angle)
3727

38-
# otherwise, just take the inverse of the angle to make
39-
# it positive
4028
else:
4129
angle = -angle
4230

43-
# rotate the image to deskew it
4431
(h, w) = image.shape[:2]
4532
center = (w // 2, h // 2)
4633
M = cv2.getRotationMatrix2D(center, angle, 1.0)
4734
rotated = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
4835

49-
# draw the correction angle on the image so we can validate it
5036
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
5337
print("[INFO] angle: {:.3f}".format(angle))
5438
cv2.imshow("Input", image)
5539
cv2.imshow("Rotated", rotated)

0 commit comments

Comments
 (0)