opencvc识别A4纸完整代码
时间: 2024-06-21 11:02:16 浏览: 175
基于opencv的A4纸提取显示
OpenCV可以使用霍夫变换检测A4纸,以下是完整代码:
```python
import cv2
import numpy as np
# 定义图片路径
img_path = "a4_paper.jpg"
# 读取图片
img = cv2.imread(img_path)
# 灰度化处理
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 边缘检测
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
# 使用霍夫变换检测直线
lines = cv2.HoughLines(edges, 1, np.pi / 180, 200)
# 定义变量保存检测到的四个角点坐标
pts1 = np.zeros((4, 2), dtype=np.float32)
for line in lines:
rho, theta = line
if (theta < (np.pi / 4.)) or (theta > (3. * np.pi / 4.0)):
# 水平直线
pt1 = (int(rho / np.cos(theta)), 0)
pt2 = (int((rho - edges.shape * np.sin(theta)) / np.cos(theta)), edges.shape)
# 计算交点
pts1 = np.vstack((pts1, [pt1, pt1]))
pts1 = np.vstack((pts1, [pt2, pt2]))
else:
# 垂直直线
pt1 = (0, int(rho / np.sin(theta)))
pt2 = (edges.shape, int((rho - edges.shape * np.cos(theta)) / np.sin(theta)))
# 计算交点
pts1 = np.vstack((pts1, [pt1, pt1]))
pts1 = np.vstack((pts1, [pt2, pt2]))
# 执行透视变换,提取A4纸区域
pts1 = pts1[4:]
pts2 = np.array([[0, 0], [0, 595], [842, 595], [842, 0]], dtype=np.float32)
M = cv2.getPerspectiveTransform(pts1, pts2)
dst = cv2.warpPerspective(img, M, (842, 595))
# 显示原图和处理后的图片
cv2.imshow("img", img)
cv2.imshow("dst", dst)
cv2.waitKey(0)
```
阅读全文