请帮我写一份Opencv二维码矫正代码,要求如下:1.对比度亮度调整 2.滤波降噪 3.反二值化 4.腐蚀膨胀处理 5.Canny边缘检测 6.Hough算子拟合直线 7.计算二维码四个顶点坐标 ,找到四根边界线,并计算出四个交点 8.利用顶点坐标进行仿射变换
时间: 2024-06-10 15:06:32 浏览: 103
好的,以下是 Opencv 二维码矫正代码:
```
import cv2
import numpy as np
# 加载图像
img = cv2.imread('qrcode.png')
# 对比度亮度调整
alpha = 1.5 # 对比度增强系数
beta = 30 # 亮度增强程度
adjusted_img = cv2.convertScaleAbs(img, alpha=alpha, beta=beta)
# 滤波降噪
kernel = np.ones((5, 5), np.float32) / 25
filtered_img = cv2.filter2D(adjusted_img, -1, kernel)
# 反二值化
gray_img = cv2.cvtColor(filtered_img, cv2.COLOR_BGR2GRAY)
ret, thresh_img = cv2.threshold(gray_img, 150, 255, cv2.THRESH_BINARY_INV)
# 腐蚀膨胀处理
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
processed_img = cv2.morphologyEx(thresh_img, cv2.MORPH_OPEN, kernel)
# Canny边缘检测
edges = cv2.Canny(processed_img, 100, 200)
# Hough算子拟合直线
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 100, minLineLength=100, maxLineGap=10)
# 计算二维码四个顶点坐标
pts = []
for line in lines:
x1, y1, x2, y2 = line[0]
pts.append((x1, y1))
pts.append((x2, y2))
# 找到四根边界线,并计算出四个交点
pts_array = np.array(pts)
rect = cv2.minAreaRect(pts_array)
box = np.int0(cv2.boxPoints(rect))
# 利用顶点坐标进行仿射变换
orig_pts = np.float32(box)
dst_pts = np.float32([[0, 0], [500, 0], [0, 500], [500, 500]])
matrix = cv2.getPerspectiveTransform(orig_pts, dst_pts)
warped_img = cv2.warpPerspective(img, matrix, (500, 500))
# 显示结果
cv2.imshow('Original Image', img)
cv2.imshow('Adjusted Image', adjusted_img)
cv2.imshow('Filtered Image', filtered_img)
cv2.imshow('Threshold Image', thresh_img)
cv2.imshow('Processed Image', processed_img)
cv2.imshow('Edges Image', edges)
cv2.imshow('Warped Image', warped_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文