资源简介
计算图像中物体倾斜角的大小,并根据计算出来的角度将图像旋转正,通过python实现
代码片段和文件信息
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import time
def Rotate(img angle=0.0fill=0):
“““
旋转
:param img:待旋转图像
:param angle: 旋转角度
:param fill:填充方式,默认0黑色填充
:return: img: 旋转后的图像
“““
w h = img.shape[:2]
center = (int(w / 2) int(h / 2))
rot = cv2.getRotationMatrix2D(center angle 1.0)
img = cv2.warpAffine(img rot (h w) borderValue=fill)
return img
def CalcAngle(img):
h w = img.shape[:2]
x1 y1 x2 y2 = 0 0 0 0
angle = 0
for i in range(h - 1):
if img[i][int(w / 3)] == 0 and img[i - 1][int(w / 3)] != 0:
# print(“1“int(w/3)i)
x1 y1 = int(w / 3) i
if img[i][int(w * 2 / 3)] == 0 and img[i - 1][int(w * 2 / 3)] != 0:
# print(“2“int(w*2/3)i)
x2 y2 = int(w * 2 / 3) i
if x1 != 0 and y1 != 0 and x2 != 0 and y2 != 0:
if x2 - x1 == 0 or y2 - y1 == 0:
print(u“不需要旋转“)
return 0
else:
length = (y2 - y1) / (x2 - x1)
angle = np.arctan(length) / 0.017453
if angle < -45:
angle = angle + 90
elif angle > 45:
angle = angle - 90
else:
pass
print(u“旋转角度:“ angle)
return angle
starts = time.clock()
img1=cv2.imread(“1.bmp“0)
# img=Rotate(img12255)
retimg=cv2.threshold(img1200255cv2.THRESH_BINARY)
# cv2.imshow(“0“img)
img = cv2.Canny(img 10 255 apertureSize=3)
angle=CalcAngle(img)
img=Rotate(img1angle)
ends = time.clock()
print(“time“ ends - starts “秒“)
cv2.imwrite(“00.jpg“img)
# cv2.imshow(“00“img)
cv2.waitKey(0)
cv2.destroyAllWindows()
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 1906 2018-11-06 14:01 图像旋转(角度计算并旋转)\angle.py
文件 1351350 2018-11-06 10:47 图像旋转(角度计算并旋转)\rotate.bmp
文件 8584 2018-11-06 13:32 图像旋转(角度计算并旋转)\Rotate.py
目录 0 2019-04-11 16:59 图像旋转(角度计算并旋转)
----------- --------- ---------- ----- ----
1361840 4
- 上一篇:python面试题大全
- 下一篇:python爬取100个百度百科页面信息
评论
共有 条评论