最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

OpenCV?Python身份證信息識(shí)別過(guò)程詳解

 更新時(shí)間:2022年04月11日 08:20:11   作者:wFitting  
本篇文章使用OpenCV-Python和CnOcr來(lái)實(shí)現(xiàn)身份證信息識(shí)別的案例,本篇文章使用的Python版本為3.6,OpenCV-Python版本為3.4.1.15,如果是4.x版本的同學(xué),可能會(huì)有一些Api操作不同,下面跟隨小編看下OpenCV?Python身份證信息識(shí)別過(guò)程

本篇文章使用OpenCV-Python和CnOcr來(lái)實(shí)現(xiàn)身份證信息識(shí)別的案例。想要識(shí)別身份證中的文本信息,總共分為三大步驟:一、通過(guò)預(yù)處理身份證區(qū)域檢測(cè)查找;二、身份證文本信息提??;三、身份證文本信息識(shí)別。下面來(lái)看一下識(shí)別的具體過(guò)程CnOcr官網(wǎng)。識(shí)別過(guò)程視頻

前置環(huán)境

這里的環(huán)境需要安裝OpenCV-Python,Numpy和CnOcr。本篇文章使用的Python版本為3.6,OpenCV-Python版本為3.4.1.15,如果是4.x版本的同學(xué),可能會(huì)有一些Api操作不同。這些依賴的安裝和介紹,我就不在這里贅述了,均是使用Pip進(jìn)行安裝。

識(shí)別過(guò)程

首先,導(dǎo)入所需要的依賴cv2,numpy,cnocr并創(chuàng)建一個(gè)show圖像的函數(shù),方便后面使用:

import cv2
import numpy as np
from cnocr import CnOcr
def show(image, window_name):
    cv2.namedWindow(window_name, 0)
    cv2.imshow(window_name, image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
# 加載CnOcr的模型
ocr = CnOcr(model_name='densenet_lite_136-gru')

身份證區(qū)域查找

通過(guò)對(duì)加載圖像的灰度處理–>濾波處理–>二值處理–>邊緣檢測(cè)–>膨脹處理–>輪廓查找–>透視變換(校正)–>圖像旋轉(zhuǎn)–>固定圖像大小一系列處理之后,我們便可以清晰的裁剪出身份證的具體區(qū)域。

原始圖像

使用OpenCV的imread方法讀取本地圖片。

image = cv2.imread('card.png')
show(image, "image")

在這里插入圖片描述

灰度處理

將三通道BGR圖像轉(zhuǎn)化為灰度圖像,因?yàn)橐幌翺penCV操作都是需要基于灰度圖像進(jìn)行的。

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
show(gray, "gray")

在這里插入圖片描述

中值濾波

使用濾波處理,也就是模糊處理,這樣可以減少一些不需要的噪點(diǎn)。

blur = cv2.medianBlur(gray, 7)
show(blur, "blur")

在這里插入圖片描述

二值處理

二值處理,非黑即白。這里通過(guò)cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU,使用OpenCV的大津法二值化,對(duì)圖像進(jìn)行處理,經(jīng)過(guò)處理后的圖像,更加清晰的分辨出了背景和身份證的區(qū)域。

threshold = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
show(threshold, "threshold")

在這里插入圖片描述

邊緣檢測(cè)

使用OpenCV中最常用的邊緣檢測(cè)方法,Canny,檢測(cè)出圖像中的邊緣。

canny = cv2.Canny(threshold, 100, 150)
show(canny, "canny")

在這里插入圖片描述

邊緣膨脹

為了使上一步邊緣檢測(cè)的邊緣更加連貫,使用膨脹處理,對(duì)白色的邊緣膨脹,即邊緣線條變得更加粗一些。

kernel = np.ones((3, 3), np.uint8)
dilate = cv2.dilate(canny, kernel, iterations=5)
show(dilate, "dilate")

在這里插入圖片描述

輪廓檢測(cè)

使用findContours對(duì)邊緣膨脹過(guò)的圖片進(jìn)行輪廓檢測(cè),可以清晰的看到背景部分還是有很多噪點(diǎn)的,所需要識(shí)別的身份證部分也被輪廓圈了起來(lái)。

binary, contours, hierarchy = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
image_copy = image.copy()
res = cv2.drawContours(image_copy, contours, -1, (255, 0, 0), 20)
show(res, "res")

在這里插入圖片描述

輪廓排序

經(jīng)過(guò)對(duì)輪廓的面積排序,我們可以準(zhǔn)確的提取出身份證的輪廓。

contours = sorted(contours, key=cv2.contourArea, reverse=True)[0]
image_copy = image.copy()
res = cv2.drawContours(image_copy, contours, -1, (255, 0, 0), 20)
show(res, "contours")

在這里插入圖片描述

透視變換

通過(guò)對(duì)輪廓近似提取出輪廓的四個(gè)頂點(diǎn),并按順序進(jìn)行排序,之后通過(guò)warpPerspective對(duì)所選圖像區(qū)域進(jìn)行透視變換,也就是對(duì)所選的圖像進(jìn)行校正處理。

epsilon = 0.02 * cv2.arcLength(contours, True)
approx = cv2.approxPolyDP(contours, epsilon, True)
n = []
for x, y in zip(approx[:, 0, 0], approx[:, 0, 1]):
    n.append((x, y))
n = sorted(n)
sort_point = []
n_point1 = n[:2]
n_point1.sort(key=lambda x: x[1])
sort_point.extend(n_point1)
n_point2 = n[2:4]
n_point2.sort(key=lambda x: x[1])
n_point2.reverse()
sort_point.extend(n_point2)
p1 = np.array(sort_point, dtype=np.float32)
h = sort_point[1][1] - sort_point[0][1]
w = sort_point[2][0] - sort_point[1][0]
pts2 = np.array([[0, 0], [0, h], [w, h], [w, 0]], dtype=np.float32)

# 生成變換矩陣
M = cv2.getPerspectiveTransform(p1, pts2)
# 進(jìn)行透視變換
dst = cv2.warpPerspective(image, M, (w, h))
# print(dst.shape)
show(dst, "dst")

在這里插入圖片描述

固定圖像大小

將圖像變正,通過(guò)對(duì)圖像的寬高進(jìn)行判斷,如果寬<高,就將圖像旋轉(zhuǎn)90°。并將圖像resize到指定大小。方便之后對(duì)圖像進(jìn)行處理。

if w < h:
    dst = np.rot90(dst)
resize = cv2.resize(dst, (1084, 669), interpolation=cv2.INTER_AREA)
show(resize, "resize")

在這里插入圖片描述

檢測(cè)身份證文本位置

經(jīng)過(guò)灰度,二值濾波和開(kāi)閉運(yùn)算后,將圖像中的文本區(qū)域主鍵顯現(xiàn)出來(lái)。

temp_image = resize.copy()
gray = cv2.cvtColor(resize, cv2.COLOR_BGR2GRAY)
show(gray, "gray")
threshold = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
show(threshold, "threshold")
blur = cv2.medianBlur(threshold, 5)
show(blur, "blur")
kernel = np.ones((3, 3), np.uint8)
morph_open = cv2.morphologyEx(blur, cv2.MORPH_OPEN, kernel)
show(morph_open, "morph_open")

在這里插入圖片描述

極度膨脹

給定一個(gè)比較大的卷積盒,進(jìn)行膨脹處理,使白色的區(qū)域加深加大。更加顯現(xiàn)出文本的區(qū)域。

kernel = np.ones((7, 7), np.uint8)
dilate = cv2.dilate(morph_open, kernel, iterations=6)
show(dilate, "dilate")

在這里插入圖片描述

輪廓查找文本區(qū)域

使用輪廓查找,將白色塊狀區(qū)域查找出來(lái)。

binary, contours, hierarchy = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
resize_copy = resize.copy()
res = cv2.drawContours(resize_copy, contours, -1, (255, 0, 0), 2)
show(res, "res")

在這里插入圖片描述

篩選出文本區(qū)域

經(jīng)過(guò)上一步輪廓檢測(cè),我們發(fā)現(xiàn),選中的輪廓中有一些噪點(diǎn),通過(guò)對(duì)圖像的觀察,使用近似輪廓,然后用以下邏輯篩選出文本區(qū)域。并定義文本描述信息,將文本區(qū)域位置信息加入到指定集合中。到這一步,可以清晰的看到,所需要的文本區(qū)域統(tǒng)統(tǒng)都被提取了出來(lái)。

labels = ['姓名', '性別', '民族', '出生年', '出生月', '出生日', '住址', '公民身份證號(hào)碼']
positions = []
data_areas = {}
resize_copy = resize.copy()
for contour in contours:
    epsilon = 0.002 * cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(contour, epsilon, True)
    x, y, w, h = cv2.boundingRect(approx)
    if h > 50 and x < 670:
        res = cv2.rectangle(resize_copy, (x, y), (x + w, y + h), (0, 255, 0), 2)
        area = gray[y:(y + h), x:(x + w)]
        blur = cv2.medianBlur(area, 3)
        data_area = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
        positions.append((x, y))
        data_areas['{}-{}'.format(x, y)] = data_area

show(res, "res")

在這里插入圖片描述

對(duì)文本區(qū)域進(jìn)行排序

發(fā)現(xiàn)文本的區(qū)域是由下到上的順序,并且x軸從左到右的的區(qū)域是無(wú)序的,所以使用以下邏輯,對(duì)文本區(qū)域進(jìn)行排序

positions.sort(key=lambda p: p[1])
result = []
index = 0
while index < len(positions) - 1:
    if positions[index + 1][1] - positions[index][1] < 10:
        temp_list = [positions[index + 1], positions[index]]
        for i in range(index + 1, len(positions)):
            if positions[i + 1][1] - positions[i][1] < 10:
                temp_list.append(positions[i + 1])
            else:
                break
        temp_list.sort(key=lambda p: p[0])
        positions[index:(index + len(temp_list))] = temp_list
        index = index + len(temp_list) - 1
    else:
        index += 1

識(shí)別文本

對(duì)文本區(qū)域使用CnOcr一一進(jìn)行識(shí)別,最后將識(shí)別結(jié)果進(jìn)行輸出。

positions.sort(key=lambda p: p[1])
result = []
index = 0
while index < len(positions) - 1:
    if positions[index + 1][1] - positions[index][1] < 10:
        temp_list = [positions[index + 1], positions[index]]
        for i in range(index + 1, len(positions)):
            if positions[i + 1][1] - positions[i][1] < 10:
                temp_list.append(positions[i + 1])
            else:
                break
        temp_list.sort(key=lambda p: p[0])
        positions[index:(index + len(temp_list))] = temp_list
        index = index + len(temp_list) - 1
    else:
        index += 1

在這里插入圖片描述

結(jié)語(yǔ)

通過(guò)以上的步驟,便成功的將身份證信息進(jìn)行了提取,過(guò)程中的一些數(shù)字參數(shù),可能會(huì)在不同的場(chǎng)景中有些許的調(diào)整。
以下放上所有的代碼:

代碼

import cv2
import numpy as np
from cnocr import CnOcr

def show(image, window_name):
    cv2.namedWindow(window_name, 0)
    cv2.imshow(window_name, image)
    # 0任意鍵終止窗口
    cv2.waitKey(0)
    cv2.destroyAllWindows()


ocr = CnOcr(model_name='densenet_lite_136-gru')

image = cv2.imread('card.png')
show(image, "image")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
show(gray, "gray")
blur = cv2.medianBlur(gray, 7)
show(blur, "blur")
threshold = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
show(threshold, "threshold")
canny = cv2.Canny(threshold, 100, 150)
show(canny, "canny")
kernel = np.ones((3, 3), np.uint8)
dilate = cv2.dilate(canny, kernel, iterations=5)
show(dilate, "dilate")
binary, contours, hierarchy = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
image_copy = image.copy()
res = cv2.drawContours(image_copy, contours, -1, (255, 0, 0), 20)
show(res, "res")
contours = sorted(contours, key=cv2.contourArea, reverse=True)[0]
image_copy = image.copy()
res = cv2.drawContours(image_copy, contours, -1, (255, 0, 0), 20)
show(res, "contours")
epsilon = 0.02 * cv2.arcLength(contours, True)
approx = cv2.approxPolyDP(contours, epsilon, True)
n = []
for x, y in zip(approx[:, 0, 0], approx[:, 0, 1]):
    n.append((x, y))
n = sorted(n)
sort_point = []
n_point1 = n[:2]
n_point1.sort(key=lambda x: x[1])
sort_point.extend(n_point1)
n_point2 = n[2:4]
n_point2.sort(key=lambda x: x[1])
n_point2.reverse()
sort_point.extend(n_point2)
p1 = np.array(sort_point, dtype=np.float32)
h = sort_point[1][1] - sort_point[0][1]
w = sort_point[2][0] - sort_point[1][0]
pts2 = np.array([[0, 0], [0, h], [w, h], [w, 0]], dtype=np.float32)

M = cv2.getPerspectiveTransform(p1, pts2)
dst = cv2.warpPerspective(image, M, (w, h))
# print(dst.shape)
show(dst, "dst")
if w < h:
    dst = np.rot90(dst)
resize = cv2.resize(dst, (1084, 669), interpolation=cv2.INTER_AREA)
show(resize, "resize")
temp_image = resize.copy()
gray = cv2.cvtColor(resize, cv2.COLOR_BGR2GRAY)
show(gray, "gray")
threshold = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
show(threshold, "threshold")
blur = cv2.medianBlur(threshold, 5)
show(blur, "blur")
kernel = np.ones((3, 3), np.uint8)
morph_open = cv2.morphologyEx(blur, cv2.MORPH_OPEN, kernel)
show(morph_open, "morph_open")
kernel = np.ones((7, 7), np.uint8)
dilate = cv2.dilate(morph_open, kernel, iterations=6)
show(dilate, "dilate")
binary, contours, hierarchy = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
resize_copy = resize.copy()
res = cv2.drawContours(resize_copy, contours, -1, (255, 0, 0), 2)
show(res, "res")
labels = ['姓名', '性別', '民族', '出生年', '出生月', '出生日', '住址', '公民身份證號(hào)碼']
positions = []
data_areas = {}
resize_copy = resize.copy()
for contour in contours:
    epsilon = 0.002 * cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(contour, epsilon, True)
    x, y, w, h = cv2.boundingRect(approx)
    if h > 50 and x < 670:
        res = cv2.rectangle(resize_copy, (x, y), (x + w, y + h), (0, 255, 0), 2)
        area = gray[y:(y + h), x:(x + w)]
        blur = cv2.medianBlur(area, 3)
        data_area = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
        positions.append((x, y))
        data_areas['{}-{}'.format(x, y)] = data_area

show(res, "res")

positions.sort(key=lambda p: p[1])
result = []
index = 0
while index < len(positions) - 1:
    if positions[index + 1][1] - positions[index][1] < 10:
        temp_list = [positions[index + 1], positions[index]]
        for i in range(index + 1, len(positions)):
            if positions[i + 1][1] - positions[i][1] < 10:
                temp_list.append(positions[i + 1])
            else:
                break
        temp_list.sort(key=lambda p: p[0])
        positions[index:(index + len(temp_list))] = temp_list
        index = index + len(temp_list) - 1
    else:
        index += 1
for index in range(len(positions)):
    position = positions[index]
    data_area = data_areas['{}-{}'.format(position[0], position[1])]
    ocr_data = ocr.ocr(data_area)
    ocr_result = ''.join([''.join(result[0]) for result in ocr_data]).replace(' ', '')
    # print('{}:{}'.format(labels[index], ocr_result))
    result.append('{}:{}'.format(labels[index], ocr_result))
    show(data_area, "data_area")

for item in result:
    print(item)
show(res, "res")

到此這篇關(guān)于OpenCV Python身份證信息識(shí)別的文章就介紹到這了,更多相關(guān)Python身份證信息識(shí)別內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python并行庫(kù)joblib之delayed函數(shù)與Parallel函數(shù)詳解

    Python并行庫(kù)joblib之delayed函數(shù)與Parallel函數(shù)詳解

    這篇文章主要介紹了Python并行庫(kù)joblib之delayed函數(shù)與Parallel函數(shù)詳解,Joblib就是一個(gè)可以簡(jiǎn)單地將Python代碼轉(zhuǎn)換為并行計(jì)算模式的軟件包,它可非常簡(jiǎn)單并行我們的程序,從而提高計(jì)算速度,需要的朋友可以參考下
    2023-08-08
  • Python常用庫(kù)Numpy進(jìn)行矩陣運(yùn)算詳解

    Python常用庫(kù)Numpy進(jìn)行矩陣運(yùn)算詳解

    這篇文章主要介紹了Python常用庫(kù)Numpy進(jìn)行矩陣運(yùn)算詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • python 搜索大文件的實(shí)例代碼

    python 搜索大文件的實(shí)例代碼

    今天小編就為大家分享一篇python 搜索大文件的實(shí)例代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-07-07
  • python實(shí)現(xiàn)發(fā)送郵件及附件功能

    python實(shí)現(xiàn)發(fā)送郵件及附件功能

    這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)發(fā)送郵件及附件功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-05-05
  • OpenCV-Python實(shí)現(xiàn)多模板匹配

    OpenCV-Python實(shí)現(xiàn)多模板匹配

    模板匹配就是在一幅圖像中尋找另一幅模板圖像最匹配,本文主要實(shí)現(xiàn)了多模板匹配,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-06-06
  • python自定義分頁(yè)器的實(shí)現(xiàn)

    python自定義分頁(yè)器的實(shí)現(xiàn)

    這篇文章主要介紹了python自定義分頁(yè)器的實(shí)現(xiàn),通過(guò)自定義分頁(yè)器封裝展開(kāi)主題并對(duì)其實(shí)用方法簡(jiǎn)單介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-04-04
  • PyTorch實(shí)現(xiàn)手寫數(shù)字的識(shí)別入門小白教程

    PyTorch實(shí)現(xiàn)手寫數(shù)字的識(shí)別入門小白教程

    這篇文章主要介紹了python實(shí)現(xiàn)手寫數(shù)字識(shí)別,非常適合小白入門學(xué)習(xí),本文通過(guò)實(shí)例圖文相結(jié)合給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-06-06
  • 如何使用Python破解ZIP或RAR壓縮文件密碼

    如何使用Python破解ZIP或RAR壓縮文件密碼

    這篇文章主要介紹了如何使用Python破解ZIP或RAR壓縮文件密碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-01-01
  • Python使用回溯法子集樹(shù)模板解決迷宮問(wèn)題示例

    Python使用回溯法子集樹(shù)模板解決迷宮問(wèn)題示例

    這篇文章主要介紹了Python使用回溯法解決迷宮問(wèn)題,簡(jiǎn)單講述了迷宮問(wèn)題的原理并結(jié)合實(shí)例形式分析了Python基于回溯法子集樹(shù)模板解決迷宮問(wèn)題的相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下
    2017-09-09
  • python 對(duì)象和json互相轉(zhuǎn)換方法

    python 對(duì)象和json互相轉(zhuǎn)換方法

    下面小編就為大家分享一篇python 對(duì)象和json互相轉(zhuǎn)換方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-03-03

最新評(píng)論

永宁县| 和林格尔县| 武城县| 裕民县| 汨罗市| 视频| 屏山县| 民和| 普洱| 巧家县| 无为县| 天峨县| 佛教| 分宜县| 南康市| 固安县| 鄂温| 塘沽区| 石景山区| 榆社县| 拉萨市| 越西县| 常德市| 宁海县| 平顺县| 叙永县| 乐平市| 秦皇岛市| 雅安市| 灌南县| 永靖县| 北海市| 兴隆县| 荥阳市| 洛川县| 都江堰市| 桓仁| 慈溪市| 莲花县| 龙门县| 连江县|