【问题标题】:Use pytesseract OCR to recognize text from an image使用 pytesseract OCR 识别图像中的文本
【发布时间】:2016-10-11 06:15:55
【问题描述】:

我需要使用 Pytesseract 从这张图片中提取文字:

和代码:

from PIL import Image, ImageEnhance, ImageFilter
import pytesseract
path = 'pic.gif'
img = Image.open(path)
img = img.convert('RGBA')
pix = img.load()
for y in range(img.size[1]):
    for x in range(img.size[0]):
        if pix[x, y][0] < 102 or pix[x, y][1] < 102 or pix[x, y][2] < 102:
            pix[x, y] = (0, 0, 0, 255)
        else:
            pix[x, y] = (255, 255, 255, 255)
img.save('temp.jpg')
text = pytesseract.image_to_string(Image.open('temp.jpg'))
# os.remove('temp.jpg')
print(text)

而“temp.jpg”是

还不错,但是打印的结果是,2 WW 文本不对2HHH,那要怎么去掉那些黑点呢?

【问题讨论】:

    标签: python image image-processing computer-vision ocr


    【解决方案1】:

    这是我的解决方案:

    import pytesseract
    from PIL import Image, ImageEnhance, ImageFilter
    
    im = Image.open("temp.jpg") # the second one 
    im = im.filter(ImageFilter.MedianFilter())
    enhancer = ImageEnhance.Contrast(im)
    im = enhancer.enhance(2)
    im = im.convert('1')
    im.save('temp2.jpg')
    text = pytesseract.image_to_string(Image.open('temp2.jpg'))
    print(text)
    

    【讨论】:

    • 嗨,当我使用此代码时,出现以下错误“UnicodeEncodeError: 'charmap' codec can't encode characters in position 11-12: c haracter maps to ”。你能建议一个方法来克服这个
    • @MAK 你需要在你的windows上安装win-unicode-console
    【解决方案2】:

    这是一个使用 OpenCV 和 Pytesseract OCR 的简单方法。要对图像执行 OCR,对图像进行预处理很重要。这个想法是获得一个处理后的图像,其中要提取的文本是黑色的,背景是白色的。为此,我们可以转换为grayscale,应用轻微的Gaussian blur,然后Otsu's threshold 以获得二值图像。从这里,我们可以应用morphological operations 来消除噪音。最后我们反转图像。我们使用--psm 6 配置选项执行文本提取,以假设单个统一的文本块。查看here 了解更多选项。


    这是图像处理管道的可视化:

    输入图像

    转为灰度-&gt;高斯模糊-&gt;大津的阈值

    请注意有微小的噪音规格,要去除它们,我们可以执行形态学操作

    最后我们反转图像

    Pytesseract OCR 的结果

    2HHH
    

    代码

    import cv2
    import pytesseract
    
    pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
    
    # Grayscale, Gaussian blur, Otsu's threshold
    image = cv2.imread('1.png')
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (3,3), 0)
    thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
    
    # Morph open to remove noise and invert image
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
    opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=1)
    invert = 255 - opening
    
    # Perform text extraction
    data = pytesseract.image_to_string(invert, lang='eng', config='--psm 6')
    print(data)
    
    cv2.imshow('thresh', thresh)
    cv2.imshow('opening', opening)
    cv2.imshow('invert', invert)
    cv2.waitKey()
    

    【讨论】:

    • 这是我在 SO! 中看到的最准确、解释最清楚的答案之一!谢谢!
    【解决方案3】:

    我对我们的社区有一些不同的 pytesseract 方法。 这是我的方法

    import pytesseract
    from PIL import Image
    text = pytesseract.image_to_string(Image.open("temp.jpg"), lang='eng',
                            config='--psm 10 --oem 3 -c tessedit_char_whitelist=0123456789')
    
    print(text)
    

    【讨论】:

    • 我尝试了-psm,但没有任何效果,但在看到您的帖子后,我尝试了--psm,它解决了所有问题。很棒
    【解决方案4】:

    要直接从网上提取文字,可以试试下面的实现(making use of the first image)

    import io
    import requests
    import pytesseract
    from PIL import Image, ImageFilter, ImageEnhance
    
    response = requests.get('https://i.stack.imgur.com/HWLay.gif')
    img = Image.open(io.BytesIO(response.content))
    img = img.convert('L')
    img = img.filter(ImageFilter.MedianFilter())
    enhancer = ImageEnhance.Contrast(img)
    img = enhancer.enhance(2)
    img = img.convert('1')
    img.save('image.jpg')
    imagetext = pytesseract.image_to_string(img)
    print(imagetext)
    

    【讨论】:

      【解决方案5】:

      这是我在特定颜色频率范围内去除噪点和任意线条的小进步。

      import pytesseract
      from PIL import Image, ImageEnhance, ImageFilter
      
      im = Image.open(img)  # img is the path of the image 
      im = im.convert("RGBA")
      newimdata = []
      datas = im.getdata()
      
      for item in datas:
          if item[0] < 112 or item[1] < 112 or item[2] < 112:
              newimdata.append(item)
          else:
              newimdata.append((255, 255, 255))
      im.putdata(newimdata)
      
      im = im.filter(ImageFilter.MedianFilter())
      enhancer = ImageEnhance.Contrast(im)
      im = enhancer.enhance(2)
      im = im.convert('1')
      im.save('temp2.jpg')
      text = pytesseract.image_to_string(Image.open('temp2.jpg'),config='-c tessedit_char_whitelist=0123456789abcdefghijklmnopqrstuvwxyz -psm 6', lang='eng')
      print(text)
      

      【讨论】:

      • 某些东西从未对图像起作用,您可以编辑并重试吗?
      • @David 你能详细说明一下吗?什么不工作?
      • 嗯,暂时不记得了,但我确定这与代码无关,而是与此处上传的图像有关。您是否删除了上传?再也见不到了。
      【解决方案6】:

      你只需要通过cv2.resize放大图片的大小

      image = cv2.resize(image,(0,0),fx=7,fy=7)
      

      我的图片 200x40 -> HZUBS

      将相同的图片大小调整为 1400x300 -> A 1234(所以,这是正确的)

      然后,

      retval, image = cv2.threshold(image,200,255, cv2.THRESH_BINARY)
      image = cv2.GaussianBlur(image,(11,11),0)
      image = cv2.medianBlur(image,9)
      

      并更改参数以增强结果

      Page segmentation modes:
        0    Orientation and script detection (OSD) only.
        1    Automatic page segmentation with OSD.
        2    Automatic page segmentation, but no OSD, or OCR.
        3    Fully automatic page segmentation, but no OSD. (Default)
        4    Assume a single column of text of variable sizes.
        5    Assume a single uniform block of vertically aligned text.
        6    Assume a single uniform block of text.
        7    Treat the image as a single text line.
        8    Treat the image as a single word.
        9    Treat the image as a single word in a circle.
       10    Treat the image as a single character.
       11    Sparse text. Find as much text as possible in no particular order.
       12    Sparse text with OSD.
       13    Raw line. Treat the image as a single text line,
                  bypassing hacks that are Tesseract-specific.
      

      【讨论】:

        【解决方案7】:
        from PIL import Image, ImageEnhance, ImageFilter
        import pytesseract
        path = 'hhh.gif'
        img = Image.open(path)
        img = img.convert('RGBA')
        pix = img.load()
        for y in range(img.size[1]):
            for x in range(img.size[0]):
                if pix[x, y][0] < 102 or pix[x, y][1] < 102 or pix[x, y][2] < 102:
                    pix[x, y] = (0, 0, 0, 255)
                else:
                    pix[x, y] = (255, 255, 255, 255)
        text = pytesseract.image_to_string(Image.open('hhh.gif'))
        print(text)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-06-22
          • 2020-05-18
          • 1970-01-01
          • 1970-01-01
          • 2021-11-14
          • 1970-01-01
          • 2021-07-07
          • 2019-12-04
          相关资源
          最近更新 更多