如何使用python用霍夫变换将一个DM二维码矫正并转化成0-1矩阵计算其旋转角度和中心坐标
时间: 2024-06-11 21:06:37 浏览: 109
要使用Python对二维码进行霍夫变换(Hough Transform)进行矫正,需要先安装OpenCV库。以下是步骤:
1. 导入所需的库
```python
import cv2
import numpy as np
from matplotlib import pyplot as plt
```
2. 读取图像
```python
img = cv2.imread('qrcode.png')
```
3. 转换为灰度图像
```python
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
```
4. 边缘检测
```python
edges = cv2.Canny(gray,50,150,apertureSize = 3)
```
5. 进行霍夫变换
```python
lines = cv2.HoughLines(edges,1,np.pi/180,200)
```
6. 计算旋转角度
```python
for rho,theta in lines[0]:
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))
cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)
angle = np.arctan2(y2-y1, x2-x1) * 180.0 / np.pi
```
7. 计算中心坐标
```python
rows,cols = img.shape[:2]
M = cv2.getRotationMatrix2D((cols/2,rows/2),angle,1)
dst = cv2.warpAffine(img,M,(cols,rows))
gray = cv2.cvtColor(dst,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
M = cv2.moments(thresh)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
```
8. 转化为0-1矩阵
```python
binary = cv2.threshold(gray, 0, 1, cv2.THRESH_BINARY)[1]
```
完整代码如下:
```python
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('qrcode.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)
for rho,theta in lines[0]:
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))
cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)
angle = np.arctan2(y2-y1, x2-x1) * 180.0 / np.pi
rows,cols = img.shape[:2]
M = cv2.getRotationMatrix2D((cols/2,rows/2),angle,1)
dst = cv2.warpAffine(img,M,(cols,rows))
gray = cv2.cvtColor(dst,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
M = cv2.moments(thresh)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
binary = cv2.threshold(gray, 0, 1, cv2.THRESH_BINARY)[1]
plt.imshow(binary,cmap = 'gray')
plt.show()
print("旋转角度为:", angle)
print("中心坐标为:", cx, cy)
```
需要注意的是,该方法只适用于二维码是正方形的情况,如果是长方形的话需要进行额外的处理。
阅读全文