-
Notifications
You must be signed in to change notification settings - Fork 0
/
rotate_image.py
70 lines (54 loc) · 1.86 KB
/
rotate_image.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 1 21:41:05 2023
@author: horry
"""
import argparse
import pathlib
import time
from typing import Optional
import cv2
import matplotlib.pyplot as plt
import numpy as np
import skimage
import skimage.transform as skt
import utils
def find_angle_lines(lines: np.ndarray) -> float:
array_angle = np.round(np.degrees((np.arctan2( lines[:,0,1]-lines[:,0,3] , lines[:,0,0]-lines[:,0,2] )))%90,2)
max_angle_count = 0
for ang in array_angle:
if(max_angle_count < np.count_nonzero(array_angle == ang) ):
max_angle_count = np.count_nonzero(array_angle == ang)
angle = ang
return angle
def find_rotation(img: np.ndarray, is_plot_edges: bool) -> float:
lines = utils.detect_hough_line_canny(img, is_plot_edges)
angle = find_angle_lines(lines)
return angle
def rotate(img: np.ndarray, is_plot_edges: bool) -> np.ndarray:
"""
Given an angle rotate the image correctly
Parameters
----------
img : np.ndarray
DESCRIPTION.
Returns
-------
TYPE
DESCRIPTION.
"""
angle = find_rotation(img, is_plot_edges)
center = tuple(map(lambda x: x/2, img.shape[:2]))
rotated = skt.rotate(img, angle, center=center,resize=True)
return (256*rotated).astype(np.uint8)
if __name__ == "__main__":
parser = utils.get_base_parser("Function to rotate a file")
parser.add_argument("--save-edges", help="save the edges", action="store_true")
args = parser.parse_args()
# read image
img = utils.read(args.input)
t = time.time()
rotated = rotate(img, args.save_edges)
print(f" time to rotate: {time.time() - t}")
out_path = utils.get_output_path(args.input, "_rotated", args.output)
cv2.imwrite(str(out_path), rotated)