[
  {
    "path": ".gitignore",
    "content": "*.py[co]\n\n# Packages\n*.egg\n*.egg-info\ndist\nbuild\neggs\nparts\nbin\nvar\nsdist\ndevelop-eggs\n.installed.cfg\n\n# Installer logs\npip-log.txt\n\n# Unit test / coverage reports\n.coverage\n.tox\n\n#Translations\n*.mo\n\n#Mr Developer\n.mr.developer.cfg\n"
  },
  {
    "path": "LICENSE",
    "content": "Copyright (c) 2012, Jason Funk <jasonlfunk@gmail.com>\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software\nand associated documentation files (the \"Software\"), to deal in the Software without restriction,\nincluding without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial\nportions of the Software.\n \nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT\nLIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "ocr-text-extraction\n===================\n\nI am not actively supporting this script. It was just an experiment.\n\nProcesses an image to extract the text portions. Primarily\nused for pre-processing for performing OCR.\n\nImplemented in Python using OpenCV.\n\nBased on the paper \"Font and Background Color Independent Text Binarization\" by\nT Kasar, J Kumar and A G Ramakrishnan\nhttp://www.m.cs.osakafu-u.ac.jp/cbdar2007/proceedings/papers/O1-1.pdf\n\nCopyright (c) 2012, Jason Funk <jasonlfunk@gmail.com>\n"
  },
  {
    "path": "extract_text",
    "content": "#!/usr/bin/python\n\n# Processes an image to extract the text portions. Primarily\n# used for pre-processing for performing OCR.\n\n# Based on the paper \"Font and Background Color Independent Text Binarization\" by\n# T Kasar, J Kumar and A G Ramakrishnan\n# http://www.m.cs.osakafu-u.ac.jp/cbdar2007/proceedings/papers/O1-1.pdf\n\n# Copyright (c) 2012, Jason Funk <jasonlfunk@gmail.com>\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software\n# and associated documentation files (the \"Software\"), to deal in the Software without restriction,\n# including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial\n# portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT\n# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport cv2\nimport numpy as np\nimport sys\nimport os.path\n\nif len(sys.argv) != 3:\n    print \"%s input_file output_file\" % (sys.argv[0])\n    sys.exit()\nelse:\n    input_file = sys.argv[1]\n    output_file = sys.argv[2]\n\nif not os.path.isfile(input_file):\n    print \"No such file '%s'\" % input_file\n    sys.exit()\n\nDEBUG = 0\n\n\n# Determine pixel intensity\n# Apparently human eyes register colors differently.\n# TVs use this formula to determine\n# pixel intensity = 0.30R + 0.59G + 0.11B\ndef ii(xx, yy):\n    global img, img_y, img_x\n    if yy >= img_y or xx >= img_x:\n        #print \"pixel out of bounds (\"+str(y)+\",\"+str(x)+\")\"\n        return 0\n    pixel = img[yy][xx]\n    return 0.30 * pixel[2] + 0.59 * pixel[1] + 0.11 * pixel[0]\n\n\n# A quick test to check whether the contour is\n# a connected shape\ndef connected(contour):\n    first = contour[0][0]\n    last = contour[len(contour) - 1][0]\n    return abs(first[0] - last[0]) <= 1 and abs(first[1] - last[1]) <= 1\n\n\n# Helper function to return a given contour\ndef c(index):\n    global contours\n    return contours[index]\n\n\n# Count the number of real children\ndef count_children(index, h_, contour):\n    # No children\n    if h_[index][2] < 0:\n        return 0\n    else:\n        #If the first child is a contour we care about\n        # then count it, otherwise don't\n        if keep(c(h_[index][2])):\n            count = 1\n        else:\n            count = 0\n\n            # Also count all of the child's siblings and their children\n        count += count_siblings(h_[index][2], h_, contour, True)\n        return count\n\n\n# Quick check to test if the contour is a child\ndef is_child(index, h_):\n    return get_parent(index, h_) > 0\n\n\n# Get the first parent of the contour that we care about\ndef get_parent(index, h_):\n    parent = h_[index][3]\n    while not keep(c(parent)) and parent > 0:\n        parent = h_[parent][3]\n\n    return parent\n\n\n# Count the number of relevant siblings of a contour\ndef count_siblings(index, h_, contour, inc_children=False):\n    # Include the children if necessary\n    if inc_children:\n        count = count_children(index, h_, contour)\n    else:\n        count = 0\n\n    # Look ahead\n    p_ = h_[index][0]\n    while p_ > 0:\n        if keep(c(p_)):\n            count += 1\n        if inc_children:\n            count += count_children(p_, h_, contour)\n        p_ = h_[p_][0]\n\n    # Look behind\n    n = h_[index][1]\n    while n > 0:\n        if keep(c(n)):\n            count += 1\n        if inc_children:\n            count += count_children(n, h_, contour)\n        n = h_[n][1]\n    return count\n\n\n# Whether we care about this contour\ndef keep(contour):\n    return keep_box(contour) and connected(contour)\n\n\n# Whether we should keep the containing box of this\n# contour based on it's shape\ndef keep_box(contour):\n    xx, yy, w_, h_ = cv2.boundingRect(contour)\n\n    # width and height need to be floats\n    w_ *= 1.0\n    h_ *= 1.0\n\n    # Test it's shape - if it's too oblong or tall it's\n    # probably not a real character\n    if w_ / h_ < 0.1 or w_ / h_ > 10:\n        if DEBUG:\n            print \"\\t Rejected because of shape: (\" + str(xx) + \",\" + str(yy) + \",\" + str(w_) + \",\" + str(h_) + \")\" + \\\n                  str(w_ / h_)\n        return False\n    \n    # check size of the box\n    if ((w_ * h_) > ((img_x * img_y) / 5)) or ((w_ * h_) < 15):\n        if DEBUG:\n            print \"\\t Rejected because of size\"\n        return False\n\n    return True\n\n\ndef include_box(index, h_, contour):\n    if DEBUG:\n        print str(index) + \":\"\n        if is_child(index, h_):\n            print \"\\tIs a child\"\n            print \"\\tparent \" + str(get_parent(index, h_)) + \" has \" + str(\n                count_children(get_parent(index, h_), h_, contour)) + \" children\"\n            print \"\\thas \" + str(count_children(index, h_, contour)) + \" children\"\n\n    if is_child(index, h_) and count_children(get_parent(index, h_), h_, contour) <= 2:\n        if DEBUG:\n            print \"\\t skipping: is an interior to a letter\"\n        return False\n\n    if count_children(index, h_, contour) > 2:\n        if DEBUG:\n            print \"\\t skipping, is a container of letters\"\n        return False\n\n    if DEBUG:\n        print \"\\t keeping\"\n    return True\n\n# Load the image\norig_img = cv2.imread(input_file)\n\n# Add a border to the image for processing sake\nimg = cv2.copyMakeBorder(orig_img, 50, 50, 50, 50, cv2.BORDER_CONSTANT)\n\n# Calculate the width and height of the image\nimg_y = len(img)\nimg_x = len(img[0])\n\nif DEBUG:\n    print \"Image is \" + str(len(img)) + \"x\" + str(len(img[0]))\n\n#Split out each channel\nblue, green, red = cv2.split(img)\n\n# Run canny edge detection on each channel\nblue_edges = cv2.Canny(blue, 200, 250)\ngreen_edges = cv2.Canny(green, 200, 250)\nred_edges = cv2.Canny(red, 200, 250)\n\n# Join edges back into image\nedges = blue_edges | green_edges | red_edges\n\n# Find the contours\ncontours, hierarchy = cv2.findContours(edges.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n\nhierarchy = hierarchy[0]\n\nif DEBUG:\n    processed = edges.copy()\n    rejected = edges.copy()\n\n# These are the boxes that we are determining\nkeepers = []\n\n# For each contour, find the bounding rectangle and decide\n# if it's one we care about\nfor index_, contour_ in enumerate(contours):\n    if DEBUG:\n        print \"Processing #%d\" % index_\n\n    x, y, w, h = cv2.boundingRect(contour_)\n\n    # Check the contour and it's bounding box\n    if keep(contour_) and include_box(index_, hierarchy, contour_):\n        # It's a winner!\n        keepers.append([contour_, [x, y, w, h]])\n        if DEBUG:\n            cv2.rectangle(processed, (x, y), (x + w, y + h), (100, 100, 100), 1)\n            cv2.putText(processed, str(index_), (x, y - 5), cv2.FONT_HERSHEY_PLAIN, 1, (255, 255, 255))\n    else:\n        if DEBUG:\n            cv2.rectangle(rejected, (x, y), (x + w, y + h), (100, 100, 100), 1)\n            cv2.putText(rejected, str(index_), (x, y - 5), cv2.FONT_HERSHEY_PLAIN, 1, (255, 255, 255))\n\n# Make a white copy of our image\nnew_image = edges.copy()\nnew_image.fill(255)\nboxes = []\n\n# For each box, find the foreground and background intensities\nfor index_, (contour_, box) in enumerate(keepers):\n\n    # Find the average intensity of the edge pixels to\n    # determine the foreground intensity\n    fg_int = 0.0\n    for p in contour_:\n        fg_int += ii(p[0][0], p[0][1])\n\n    fg_int /= len(contour_)\n    if DEBUG:\n        print \"FG Intensity for #%d = %d\" % (index_, fg_int)\n\n    # Find the intensity of three pixels going around the\n    # outside of each corner of the bounding box to determine\n    # the background intensity\n    x_, y_, width, height = box\n    bg_int = \\\n        [\n            # bottom left corner 3 pixels\n            ii(x_ - 1, y_ - 1),\n            ii(x_ - 1, y_),\n            ii(x_, y_ - 1),\n\n            # bottom right corner 3 pixels\n            ii(x_ + width + 1, y_ - 1),\n            ii(x_ + width, y_ - 1),\n            ii(x_ + width + 1, y_),\n\n            # top left corner 3 pixels\n            ii(x_ - 1, y_ + height + 1),\n            ii(x_ - 1, y_ + height),\n            ii(x_, y_ + height + 1),\n\n            # top right corner 3 pixels\n            ii(x_ + width + 1, y_ + height + 1),\n            ii(x_ + width, y_ + height + 1),\n            ii(x_ + width + 1, y_ + height)\n        ]\n\n    # Find the median of the background\n    # pixels determined above\n    bg_int = np.median(bg_int)\n\n    if DEBUG:\n        print \"BG Intensity for #%d = %s\" % (index_, repr(bg_int))\n\n    # Determine if the box should be inverted\n    if fg_int >= bg_int:\n        fg = 255\n        bg = 0\n    else:\n        fg = 0\n        bg = 255\n\n        # Loop through every pixel in the box and color the\n        # pixel accordingly\n    for x in range(x_, x_ + width):\n        for y in range(y_, y_ + height):\n            if y >= img_y or x >= img_x:\n                if DEBUG:\n                    print \"pixel out of bounds (%d,%d)\" % (y, x)\n                continue\n            if ii(x, y) > fg_int:\n                new_image[y][x] = bg\n            else:\n                new_image[y][x] = fg\n\n# blur a bit to improve ocr accuracy\nnew_image = cv2.blur(new_image, (2, 2))\ncv2.imwrite(output_file, new_image)\nif DEBUG:\n    cv2.imwrite('edges.png', edges)\n    cv2.imwrite('processed.png', processed)\n    cv2.imwrite('rejected.png', rejected)\n"
  }
]