import cv2
import numpy as np
import math
def fourier_demo():
img=cv2.imread('C:/Users/xpp/Desktop/Lena.png',0)
h,w=img.shape[:2]
new_h=cv2.getOptimalDFTSize(h)
new_w=cv2.getOptimalDFTSize(w)
right=new_w-w
bottom=new_h-h
result1=cv2.copyMakeBorder(img,0,bottom,0,right,borderType=cv2.BORDER_CONSTANT,value=0)
cv2.imshow('result1',result1)
#傅里叶变换
f=np.fft.fft2(result1)
fshift=np.fft.fftshift(f)
magnitude=np.log(np.abs(fshift))
#二值化
magnitude_uint=magnitude.astype(np.uint8)
ret, thresh=cv2.threshold(magnitude_uint,11,255,cv2.THRESH_BINARY)
print(ret)
cv2.imshow('thresh',thresh)
print(thresh.dtype)
#霍夫直线变换
lines=cv2.HoughLinesP(thresh,2,np.pi/180,30,minLineLength=40,maxLineGap=100)
print(len(lines))
lineimg=np.ones(nimg.shape,dtype=np.uint8)
lineimg=lineimg*255
piThresh=np.pi/180
pi2=np.pi/2
print(piThresh)
for line in lines:
x1,y1,x2,y2=line[0]
cv2.line(lineimg,(x1,y1),(x2,y2),(0,255,0),2)
if x2-x1==0:
continue
else:
theta=(y2-y1)/(x2-x1)
if abs(theta)<piThresh or abs(theta-pi2)<piThresh:
continue
else:
print(theta)
angle=math.atan(theta)
print(angle)
angle=angle*(180/np.pi)
print(angle)
angle=(angle-90)/(w/h)
print(angle)
center=(w//2,h//2)
M=cv2.getRotationMatrix2D(center,angle,1.0)
rotated=cv2.warpAffine(img,M,(w,h),flags=cv2.INTER_CUBIC,borderMode=cv2.BORDER_REPLICATE)
cv2.imshow('line image',lineimg)
cv2.imshow('rotated',rotated)
fourier_demo()
cv2.waitKey(0)
cv2.destroyAllWindows()
11.0 uint8 3 0.017453292519943295 0.022727272727272728 0.022723360841641067 1.3019526725788753 -88.69804732742112
算法:图像旋转矫正是通过修改幅度图像或相位图像方法来间接修改原空间图像。
链接:http://johnhany.net/2013/11/dft-based-text-rotation-correction/
本文分享自 图像处理与模式识别研究所 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有