如何使用 Python 检测和识别车牌
来源:51CTO技术栈
译者:布加迪
原文链接:https://www.makeuseof.com/python-car-license-plates-detect-and-recognize/
OpenCV-Python:您将使用这个库对输入图像进行预处理,并显示各个输出图像。 pipinstallOpenCV-Python imutils:您将使用这个库将原始输入图像裁剪成所需的宽度。 pipinstallimutils pytesseract:您将使用这个库提取车牌字符,并将它们转换成字符串。 pipinstallpytesseract pytesseract库依赖Tesseract OCR引擎进行字符识别。
importcv2 importimutils importpytesseract
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'original_image = cv2.imread('image3.jpeg')
original_image = imutils.resize(original_image, width=500 )gray_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)gray_image = cv2.bilateralFilter(gray_image, 11, 17, 17)
edged_image = cv2.Canny(gray_image, 30,200)contours, new = cv2.findContours(edged_image.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)img1 = original_image.copy()cv2.drawContours(img1, contours, -1, (0, 255, 0), 3)cv2.imshow("img1", img1)
contours = sorted(contours, key = cv2.contourArea, reverse = True)[:30]# stores the license plate contourscreenCnt = Noneimg2 = original_image.copy()# draws top 30 contourscv2.drawContours(img2, contours, -1, (0, 255, 0), 3)cv2.imshow("img2", img2)
count = 0idx = 7for c in contours:# approximate the license plate contourcontour_perimeter = cv2.arcLength(c, True)approx = cv2.approxPolyDP(c, 0.018 * contour_perimeter, True)# Look for contours with 4 cornersif len(approx) == 4:screenCnt = approx# find the coordinates of the license plate contourx, y, w, h = cv2.boundingRect(c)new_img = original_image [ y: y + h, x: x + w]# stores the new imagecv2.imwrite('./'+str(idx)+'.png',new_img)idx += 1break# draws the license plate contour on original imagecv2.drawContours(original_image , [screenCnt], -1, (0, 255, 0), 3)cv2.imshow("detected license plate", original_image )
# filename of the cropped license plate imagecropped_License_Plate = './7.png'cv2.imshow("cropped license plate", cv2.imread(cropped_License_Plate))# converts the license plate characters to stringtext = pytesseract.image_to_string(cropped_License_Plate, lang='eng')
print("License plate is:", text)cv2.waitKey(0)cv2.destroyAllWindows()
程序员技术交流群
扫码进群记得备注:城市、昵称和技术方向。
阅读更多