如何使用python在图片的频域做一些处理用于将歪斜的图片改为水平
时间: 2024-05-13 07:15:58 浏览: 17
要将歪斜的图片改为水平,常用的方法是使用霍夫变换来检测图像中的直线,并根据检测到的直线角度进行旋转矫正。下面是使用python实现的步骤:
1.导入需要的库
```python
import cv2
import numpy as np
from matplotlib import pyplot as plt
```
2.读取需要处理的图片并转为灰度图像
```python
img = cv2.imread('image.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
```
3.使用Canny算法提取图像边缘
```python
edges = cv2.Canny(gray,50,150,apertureSize = 3)
```
4.使用霍夫变换检测图像中的直线
```python
lines = cv2.HoughLines(edges,1,np.pi/180,200)
```
5.遍历检测到的直线并找到最长的一条线
```python
max_len = 0
max_line = None
for line in lines:
for rho,theta in line:
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0 + 1000*(-b))
y1 = int(y0 + 1000*(a))
x2 = int(x0 - 1000*(-b))
y2 = int(y0 - 1000*(a))
length = np.sqrt((x2-x1)**2 + (y2-y1)**2)
if length > max_len:
max_len = length
max_line = line
```
6.计算最长直线的角度,并进行旋转矫正
```python
rho,theta = max_line[0]
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
angle = np.arctan2(y0,x0)/np.pi*180
M = cv2.getRotationMatrix2D((img.shape[1]//2,img.shape[0]//2),-angle,1)
img_rotated = cv2.warpAffine(img,M,(img.shape[1],img.shape[0]))
```
7.显示旋转矫正后的图片
```python
plt.imshow(img_rotated)
plt.show()
```
完整代码如下:
```python
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('image.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
lines = cv2.HoughLines(edges,1,np.pi/180,200)
max_len = 0
max_line = None
for line in lines:
for rho,theta in line:
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0 + 1000*(-b))
y1 = int(y0 + 1000*(a))
x2 = int(x0 - 1000*(-b))
y2 = int(y0 - 1000*(a))
length = np.sqrt((x2-x1)**2 + (y2-y1)**2)
if length > max_len:
max_len = length
max_line = line
rho,theta = max_line[0]
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
angle = np.arctan2(y0,x0)/np.pi*180
M = cv2.getRotationMatrix2D((img.shape[1]//2,img.shape[0]//2),-angle,1)
img_rotated = cv2.warpAffine(img,M,(img.shape[1],img.shape[0]))
plt.imshow(img_rotated)
plt.show()
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)