使用Python OpenCV从车牌图像中提取数字和字母

我想检测然后从该图像中提取字母和数字。我刚刚开始学习OpenCV,我认为可以使用该lib来完成。您在下面有我使用的图像和所需的输出。 这是我的代码:

import cv2

# read original image
img = cv2.imread('image.jpg')
cv2.imshow('original',img)
cv2.waitKey(0)


# convert it to gray and apply filter 
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #convert to grey scale
gray = cv2.bilateralFilter(gray,11,17,17)
cv2.imshow('gray',gray)
cv2.waitKey(0)

#apply treshold
thresh = cv2.threshold(gray,10,255,cv2.THRESH_OTSU)[1]
cv2.imshow('thresh',thresh)
cv2.waitKey(0)

这是图片:

使用Python OpenCV从车牌图像中提取数字和字母

我的目标是获取每个字母和数字的分开的图像(我是在油漆中完成的):

使用Python OpenCV从车牌图像中提取数字和字母

那么,我应该怎么做呢? 最好保持字母和数字的顺序相同,例如:

MXF51051

imcoolmint 回答:使用Python OpenCV从车牌图像中提取数字和字母

这是一种使用简单阈值+轮廓滤波的方法

  • 将图像转换为灰度并达到Otsu的阈值
  • 查找轮廓并使用轮廓区域进行过滤
  • 提取并保存ROI

我们首先转换为灰度,然后转换为大津的阈值以获得二进制图像

enter image description here

接下来,我们使用cv2.findContours()找到轮廓。为了保持字母/数字的顺序相同,我们将imutils.contours.sort_contours()left-to-right参数一起使用,以确保在迭代轮廓时,每个轮廓都具有正确的顺序。对于每个轮廓,我们使用最小和最大面积阈值进行过滤,以确保我们只保留所需文本的轮廓。有了过滤后的ROI后,我们就可以使用Numpy切片来提取/保存ROI。这是只包含所需文字的过滤蒙版

enter image description here

检测到的数字和字母

enter image description here

提取的ROI按正确的顺序

enter image description here

import cv2
import numpy as np
from imutils import contours

image = cv2.imread('1.jpg')
mask = np.zeros(image.shape,dtype=np.uint8)
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray,255,cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

cnts = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
(cnts,_) = contours.sort_contours(cnts,method="left-to-right")
ROI_number = 0
for c in cnts:
    area = cv2.contourArea(c)
    if area < 800 and area > 200:
        x,y,w,h = cv2.boundingRect(c)
        ROI = 255 - thresh[y:y+h,x:x+w]
        cv2.drawContours(mask,[c],-1,(255,255),-1)
        cv2.imwrite('ROI_{}.png'.format(ROI_number),ROI)
        ROI_number += 1

cv2.imshow('mask',mask)
cv2.imshow('thresh',thresh)
cv2.waitKey()
本文链接:https://www.f2er.com/3123923.html

大家都在问