args = vars(ap.parse_args())
建立了一个参数解析器,添加两个参数,然后解析它们,将它们存储为变量 args 。 两个必需的命令行参数是:
–image :要进行 OCR 处理的图像的路径。
–reference :参考 OCR-A 图像的路径。 该图像包含 OCR-A 字体中的数字 0-9,从而允许我们稍后在管道中执行模板匹配。
接下来让我们定义信用卡类型:
define a dictionary that maps the first digit of a credit card
number to the credit card type
FIRST_NUMBER = {
“3”: “American Express”,
“4”: “Visa”,
“5”: “MasterCard”,
“6”: “Discover Card”
}
信用卡类型,例如美国运通、Visa 等,可以通过检查 16 位信用卡号中的第一位数字来识别。我们定义了一个字典 FIRST_NUMBER ,它将第一个数字映射到相应的信用卡类型。 让我们通过加载参考 OCR-A 图像来启动我们的图像处理管道:
load the reference OCR-A image from disk, convert it to grayscale,
and threshold it, such that the digits appear as white on a
black background
and invert it, such that the digits appear as white on a black
ref = cv2.imread(args[“reference”])
ref = cv2.cvtColor(ref, cv2.COLOR_BGR2GRAY)
ref = cv2.threshold(ref, 10, 255, cv2.THRESH_BINARY_INV)[1]
首先,我们加载参考 OCR-A 图像,然后将其转换为灰度和阈值 + 反转。 在这些操作中的每一个中,我们存储或覆盖 ref ,我们的参考图像。
现在让我们在 OCR-A 字体图像上定位轮廓:
find contours in the OCR-A image (i.e,. the outlines of the digits)
sort them from left to right, and initialize a dictionary to map
digit name to the ROI
refCnts = cv2.findContours(ref.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
refCnts = imutils.grab_contours(refCnts)
refCnts = contours.sort_contours(refCnts, method=“left-to-right”)[0]
digits = {}
找到了参考图像中的轮廓。 然后,由于 OpenCV 2.4、3 和 4 版本如何不同地存储返回的轮廓信息,我们检查版本并对 refCnts 进行适当更改。 接下来,我们从左到右对轮廓进行排序,并初始化一个字典,digits,它将数字名称映射到感兴趣的区域。
此时,我们应该遍历轮廓,提取ROI并将其与其对应的数字相关联:
loop over the OCR-A reference contours
for (i, c) in enumerate(refCnts):