11.4OpenCV_图像预处理习题02
1.身份证号码识别(结果:身份证号识别结果为:911124198108030024)
import cv2
import numpy as np
import paddlehub as hub
def get_text():
img = cv2.imread("images1/images/shenfen03.jpg")
# 灰度化
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 高斯
gs_img = cv2.GaussianBlur(gray_img, (9, 9), 0)
# 腐蚀
ero_img = cv2.erode(gs_img, np.ones((11, 11), np.uint8))
# 边缘
cany_img = cv2.Canny(ero_img, 70, 300)
cv2.imshow("Canny Image", cany_img)
# 轮廓
contours, _ = cv2.findContours(cany_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# 创建一个与原始图像同样大小的黑色图像
contour_img = np.zeros_like(img)
# 在黑色图像上绘制轮廓
cv2.drawContours(contour_img, contours, -1, (255, 255, 255), 2)
# 显示轮廓图像
cv2.imshow("Contours", contour_img)
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
print(w,h)
if w > 200 and h < 70:
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
out_img = img[y:y + h, x:x + w]
# # 绘制所有轮廓的矩形框
# for contour in contours:
# x, y, w, h = cv2.boundingRect(contour)
# # 移除条件判断,为每个轮廓绘制矩形框
# cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow("title", img)
# 显示原始图像上的矩形
cv2.imshow("title", out_img)
cv2.waitKey(0)
#加载模型
ocr = hub.Module(name="chinese_ocr_db_crnn_server")
#识别文本
results = ocr.recognize_text(images=[out_img])
for result in results:
data = result['data']
for x in data:
print('文本: ', x['text'])
cv2.destroyAllWindows()
if __name__ == "__main__":
get_text()
2.车牌识别
import cv2
import numpy as np
import paddlehub as hub
def get_text():
img = cv2.imread("images1/images/car6.png")
# 灰度化
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 顶帽
eroded = cv2.morphologyEx(gray_img, cv2.MORPH_TOPHAT, np.ones((9,9), np.uint8))
# 高斯
gs_img = cv2.GaussianBlur(eroded, (9, 9), 2)
# 边缘
cany_img = cv2.Canny(gs_img, 170, 180)
# 膨胀
eroded2 = cv2.dilate(cany_img,np.ones((17,17), np.uint8), iterations=2)
# 轮廓
contours, _ = cv2.findContours(eroded2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# 创建一个与原始图像同样大小的黑色图像
contour_img = np.zeros_like(img)
# 在黑色图像上绘制轮廓
cv2.drawContours(contour_img, contours, -1, (255, 255, 255), 2)
# 显示轮廓图像
cv2.imshow("Contours", contour_img)
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
print(w,h)
if w > 20 and h > 20:
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
out_img = img[y:y + h, x:x + w]
cv2.imshow("title", out_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# # 绘制所有轮廓的矩形框
# for contour in contours:
# x, y, w, h = cv2.boundingRect(contour)
# # 移除条件判断,为每个轮廓绘制矩形框
# cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
# cv2.imshow("title", img)
# 显示原始图像上的矩形
#加载模型
ocr = hub.Module(name="chinese_ocr_db_crnn_server")
#识别文本
results = ocr.recognize_text(images=[out_img])
for result in results:
data = result['data']
for x in data:
print('文本: ', x['text'])
if __name__ == "__main__":
get_text()
原文地址:https://blog.csdn.net/gs1we1/article/details/143495307
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!