open cv -答题卡识别
© Fu Xianjun. All Rights Reserved.
如何使用open cv 对答题卡的识别?
一、首先我们要进行的是图像的预处理、轮廓检测
分为五个步骤
1、读取图片
2、灰度处理
3、高斯滤波
4、边缘检测
5、轮廓检测与绘制
代码如下
import cv2
import numpy as np
# 正确答案
ANSWER_KEY = {
0: 1, 1: 4, 2: 0, 3: 3, 4: 1}
def cv_show(name,img):
cv2.imshow(name, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 读取输入
image = cv2.imread("test_01.png")
contours_img = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
cv_show('blurred',blurred)
edged = cv2.Canny(blurred, 75, 200)
cv_show('edged',edged)
# 轮廓检测
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,\
cv2.CHAIN_APPROX_SIMPLE)[0]
cv2.drawContours(contours_img,cnts,-1,(0,0,255),3)
cv_show('contours_img',contours_img)
运行结果如图
二、其次我们要进行对图像轮廓排序,透视变换
分为四个步骤
1、遍历轮廓
2、轮廓排序
3、四点定位
4、透视变换
代码如下
def order_points(pts):
# 一共4个坐标点
rect = np.zeros((4, 2), dtype = "float32")
# 按顺序找到对应坐标0123分别是 左上,右上,右下,左下
# 计算左上,右下
s = pts.sum(axis = 1)
rect[0] = pts