{"id":1088,"date":"2019-10-17T09:25:42","date_gmt":"2019-10-17T09:25:42","guid":{"rendered":"https:\/\/muthu.co\/?p=1088"},"modified":"2021-05-24T02:48:54","modified_gmt":"2021-05-24T02:48:54","slug":"algorithm-for-detecting-and-extracting-number-plates-from-images-of-cars","status":"publish","type":"post","link":"http:\/\/write.muthu.co\/algorithm-for-detecting-and-extracting-number-plates-from-images-of-cars\/","title":{"rendered":"Algorithm for detecting and extracting number plates from images of cars"},"content":{"rendered":"\n

Abstract<\/h2>\n\n\n\n

This article presents a method for automatic detection and extraction of number plates from the images of cars<\/span>. There are usually three steps in an Automatic Number Plate Recognition (ANPR) system. The first one is to binarize the image and separate the background from the foreground. The Foreground contains the numbers of the number plate usually with strong edges. The second step is to identify the number plate in the foreground pixels. The last step is the OCR of the identified number images. Each step has its own set of algorithms. <\/span><\/p>\n\n\n\n

In this article, I will be focussing on the second step, the extraction of the number plate from the car. I am assuming a good algorithm for thresholding already in place. I will explain good thresholding algorithms in my future posts.<\/p>\n\n\n\n

The key idea is to first run a connected component labeling on the thresholded image. Then identify the components with numbers based on the fact that the numbers usually lie in a straight line. The numbers also have similar heights and widths. Even when the number plate is not parallel to the horizontal plane, it still is in a straight line with each other.<\/p>\n\n\n\n

Introduction<\/h2>\n\n\n\n

License plate recognition (LPR), or automatic number plate recognition (ANPR), is the use of video captured images from traffic surveillance cameras for the automatic identi\ufb01cation of a vehicle through its license plate. LPR attempts to make the reading automatic by processing sets of images captured by cameras, often setup at \ufb01xed locations on roads and at parking lot entrances. ANPR was invented in 1976 at the Police Scientific Development Branch in Britain and since then this had been an actively researched field with many papers published with a goal to make the ANPR systems faster and more accurate in their recognitions.There are seven primary algorithms that the software requires for identifying a license plate as described here in this wikipedia article [4] :<\/p>\n\n\n\n

  1. Plate localization \u2013 responsible for finding and isolating the plate on the picture.<\/li>
  2. Plate orientation and sizing \u2013 compensates for the skew of the plate and adjusts the dimensions to the required size.<\/li>
  3. Normalization \u2013 adjusts the brightness and contrast of the image.<\/li>
  4. Character segmentation \u2013 finds the individual characters on the plates.<\/li>
  5. Optical character recognition.<\/li>
  6. Syntactical\/Geometrical analysis \u2013 check characters and positions against country-specific rules.<\/li>
  7. The averaging of the recognized value over multiple fields\/images to produce a more reliable or confident result. Especially since any single image may contain a reflected light flare, be partially obscured, or other temporary effects.<\/li>
  8. In this part of the series, I would be focussing on a Plate localization algorithm inspired by multiple previously researched papers [1],[2],[3].<\/li><\/ol>\n\n\n\n

    Algorithm<\/h2>\n\n\n\n

    I will threshold the image using Otsu’s method to separate the foreground containing numbers from the background. Then apply the connected component analysis on a car image. The identified labels also contain individual letters on the license plate. One interesting fact about these numbers is that they usually fall in the same line even if the image taken by the camera is skewed. I will use this collinearity property of numbers to isolate them from other connected components in the image.<\/p>\n\n\n\n

    Take a look at the below images of licence plates.<\/p>\n\n\n\n

    \"\"\/<\/figure>\n\n\n\n

    The flow of steps in number plate localisation is in the below diagram:<\/p>\n\n\n\n

    \"\"\/<\/figure>\n\n\n\n

    Implementation:<\/h2>\n\n\n\n

    Let’s go over the steps one by one and understand how it all works out. As usual, the entire implementation notebook can be found here.<\/a><\/p>\n\n\n\n

    Step 1: Read the image and guassian blur and convert it to grayscale<\/h3>\n\n\n\n
    car = imread('http:\/\/com.dataturks.a96-i23.open.s3.amazonaws.com\/2c9fafb0646e9cf9016473f1a561002a\/94c5a151-24b5-493c-a900-017a4353b00c___3e7fd381-0ae5-4421-8a70-279ee0ec1c61_Tata-Tiago-Front-Number-Plates-Design.jpg')\ngray_img = rgb2gray(car)\nblurred_gray_img = gaussian(gray_img)\nplt.figure(figsize=(20,20))\nplt.axis(\"off\")\nplt.imshow(blurred_gray_img, cmap=\"gray\")<\/code><\/pre>\n\n\n\n
    \"grayscale<\/a><\/figure><\/div>\n\n\n\n

    Guassian blur will reduce any potential noise in the image.<\/p>\n\n\n\n

    Step 2: Binarize the image<\/h3>\n\n\n\n

    I am using the widely used Otsu threshold, though its not the suggested method when it comes to ANPR systems. There are more sophisticated algorithms published only for this step which I will be talking about in my future posts. The image selected by me as a sample works fine with Otsu method.<\/span><\/p>\n\n\n\n

    thresh = threshold_otsu(gray_img)\nbinary = invert(gray_img > thresh)<\/code><\/pre>\n\n\n\n
    \"binarized<\/a><\/figure><\/div>\n\n\n\n

    Step 3: Label the binary image using n 8-connected component algorithm<\/h3>\n\n\n\n
    label_image = label(binary, connectivity=2)\n\nfig, ax = plt.subplots(figsize=(10, 6))\nax.axis(\"off\")\nax.imshow(binary, cmap=\"gray\")\n\nfor region in regionprops(label_image):\n    minr, minc, maxr, maxc = region.bbox\n    rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,\n                              fill=False, edgecolor='red', linewidth=2)\n    ax.add_patch(rect)\n\nplt.tight_layout()\nplt.show()<\/code><\/pre>\n\n\n\n
    \"\"<\/a><\/figure><\/div>\n\n\n\n

    As you can see, there are many connected components found in the image of varied sizes and shapes. I am interested in the ones that make the number plate. <\/span>As explained in the algorithm section, I would try and remove all the other unwanted components<\/span><\/span>.<\/span><\/p>\n\n\n\n

    Step 4: Remove too large, too small regions and regions whose aspect ratio is greater than 1.<\/h3>\n\n\n\n

    The key idea of this step is to remove the regions which are too big or too small. <\/span>If the area of the region is less than 15px or greater than 1\/5th of the entire image area it <\/span><\/span>probably<\/span><\/span> is not the one which can contain our numbers, ignore them<\/span><\/span>. The standard fonts used in number plates have the width smaller than the height. So, I will remove the components having an aspect ratio less than 1.<\/span><\/p>\n\n\n\n

    fig, ax = plt.subplots(figsize=(10, 6))\nax.imshow(blurred_gray_img, cmap=\"gray\")\n\n# step 1 is to identify regions which probably contains text.\ntext_like_regions = []\nfor region in regionprops(label_image):\n    minr, minc, maxr, maxc = region.bbox\n    w = maxc - minc\n    h = maxr - minr\n    \n    asr = w\/h\n    probably_text = False\n    \n    region_area = w*h\n    \n    # The aspect ratio is constrained to lie between 0.1 and 10 to eliminate\n    # highly elongated regions\n        \n    # The size of the EB should be\n    # greater than 15 pixels but smaller than 1\/5th of the image\n    # dimension to be considered for further processing\n    \n    wid,hei = blurred_gray_img.shape\n    img_area = wid*hei\n    \n    if region_area > 15 and region_area < (0.2 * img_area) and asr < 1 and h > w:\n        #print(w, h, i, region.area, region.bbox)\n        probably_text = True\n    \n    if probably_text:\n        text_like_regions.append(region)\n        \nfor region in text_like_regions:\n    minr, minc, maxr, maxc = region.bbox\n    rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,\n                              fill=False, edgecolor='red', linewidth=2)\n    ax.add_patch(rect)\n    \nplt.tight_layout()\nplt.show()<\/code><\/pre>\n\n\n\n
    \"text<\/a><\/figure><\/div>\n\n\n\n

    The above image shows regions identified which probably contains text. We can clearly see in the above image that the number plates are collinear. Lets try and isolate them.<\/p>\n\n\n\n

    Step 5: Sort the regions by how far they are from the Y-axis, group them by their collinearity and pick the largest region.<\/h2>\n\n\n\n

    As mentioned earlier, the numbers are usually collinear. <\/span>The standard way to check collinearity is to compare the slopes between different points, sort them and group them by slope<\/span><\/span>. <\/span>But that method will not work for my case here because the corner points of the regions are not <\/span><\/span>perfectly<\/span><\/span> collinear<\/span><\/span>. I would use the angle between the three points to find if the points lie in an almost straight line. I do that by checking if the angle between three points lies between 170 and 190 degrees.<\/span><\/p>\n\n\n\n

    angle = angle_between_three_points(pmin,qmin,rmin)\nif angle > 170 and angle < 190:\n    cluster.append(r)<\/code><\/pre>\n\n\n\n

    Another important way to isolate the components with numbers is to assume that they follow a natural left to right order. So I will sort the components by their distance from the Y-Axis of the image. I will simply sort the identified regions by their column values.<\/p>\n\n\n\n

    # find the angle between the three points A,B,C\n# Angle between line BA and BC\ndef angle_between_three_points(pointA, pointB, pointC):\n    BA = pointA - pointB\n    BC = pointC - pointB\n\n    try:\n        cosine_angle = np.dot(BA, BC) \/ (np.linalg.norm(BA) * np.linalg.norm(BC))\n        angle = np.arccos(cosine_angle)\n    except:\n        print(\"exc\")\n        raise Exception('invalid cosine')\n\n    return np.degrees(angle)\n\nall_points = np.array(all_points)\n\nall_points = all_points[all_points[:,1].argsort()]\nheight, width = blurred_gray_img.shape\ngroups = []\nfor p in all_points:\n    cluster = [p]\n    lines_found = False\n    for q in all_points:\n        pmin = np.array([p[0],p[1]])\n        qmin = np.array([q[0],q[1]])\n        if p[1] < q[1] and euclidean(pmin,qmin) < 0.1 * width:\n            # first check if q is already added, if not add.\n            point_already_added = False\n            for cpoints in cluster:\n                if cpoints[0] == q[0] and cpoints[1] == q[1]:\n                    point_already_added = True\n                    break;\n            if not point_already_added:\n                cluster.append(q)\n                \n            for r in all_points:\n                rmin = np.array([r[0],r[1]])\n                last_cluster_point = np.array([cluster[-1][0],cluster[-1][1]])\n                if q[1] < r[0] and euclidean(last_cluster_point,rmin) < 0.1 * width:\n                    angle = angle_between_three_points(pmin,qmin,rmin)\n                    if angle > 170 and angle < 190:\n                        lines_found = True\n                        cluster.append(r)\n                        \n    if lines_found:\n        groups.append(np.array(cluster))\n\n# plot the longest found line on the image\nlongest = -1\nlongest_index = -1\nfor index, cluster in enumerate(groups):\n    if len(cluster) > longest:\n        longest_index = index\n        longest = len(cluster)\n\nprint(\"coordinates of licence plate\\n\")\nprint(groups[longest_index])<\/code><\/pre>\n\n\n\n

    Once we have identified the licence plates, we will plot those on the image and the output of it is as shown below.<\/p>\n\n\n\n

    \"licence<\/a><\/figure><\/div>\n\n\n\n

    The identified numbers can be further passed into an OCR system to convert into text. I will be covering it in my future posts in this series.<\/p>\n\n\n\n

    Notes:<\/h2>\n\n\n\n

    The detection of licence plate number depends a lot on the thresholding algorithm, the one I used in this article was the Otsu method which may not be well suited for most binarization techniques. I will be covering a better binarization algorithm in my future posts.<\/p>\n\n\n\n

    References:<\/h2>\n\n\n\n

    [1] T Kasar, J Kumar and A G Ramakrishnan, “Font and Background Color Independent Text Binarization”<\/em><\/a>
    [2]
    H. Bai and C. Liu, “A hybrid license plate extraction method based on edge statistics and morphology”<\/em><\/a>
    [3]
    Khalid Aboura, “Automatic Thresholding of License Plate Image Data”<\/em><\/a>
    [4]
    Automatic number-plate recognition, Wikipedia\u00a0<\/a>
    [5]
    Topological sweeping algorithm of Edelsbrunner and Guibas <\/a><\/em><\/p>\n","protected":false},"excerpt":{"rendered":"

    Abstract This article presents a method for automatic detection and extraction of number plates from the images of cars. There are usually three steps in an Automatic Number Plate Recognition (ANPR) system. The first one is to binarize the image and separate the background from the foreground. The Foreground contains the numbers of the number […]<\/p>\n","protected":false},"author":1,"featured_media":1112,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[38],"tags":[47],"_links":{"self":[{"href":"http:\/\/write.muthu.co\/wp-json\/wp\/v2\/posts\/1088"}],"collection":[{"href":"http:\/\/write.muthu.co\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/write.muthu.co\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/write.muthu.co\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/write.muthu.co\/wp-json\/wp\/v2\/comments?post=1088"}],"version-history":[{"count":3,"href":"http:\/\/write.muthu.co\/wp-json\/wp\/v2\/posts\/1088\/revisions"}],"predecessor-version":[{"id":1861,"href":"http:\/\/write.muthu.co\/wp-json\/wp\/v2\/posts\/1088\/revisions\/1861"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/write.muthu.co\/wp-json\/wp\/v2\/media\/1112"}],"wp:attachment":[{"href":"http:\/\/write.muthu.co\/wp-json\/wp\/v2\/media?parent=1088"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/write.muthu.co\/wp-json\/wp\/v2\/categories?post=1088"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/write.muthu.co\/wp-json\/wp\/v2\/tags?post=1088"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}