【问题标题】:how to get character position in pytesseract如何在pytesseract中获取角色位置
【发布时间】:2015-11-17 10:42:59
【问题描述】:

我正在尝试使用 pytesseract 库获取图像文件的字符位置。

import pytesseract
from PIL import Image
print pytesseract.image_to_string(Image.open('5.png'))

有没有获取每个角色位置的库

【问题讨论】:

    标签: python-2.7 image-processing ocr python-tesseract pytesser


    【解决方案1】:

    您是否尝试过使用 pytesseract.image_to_data()?

    data = pytesseract.image_to_data(img, output_type='dict')
    boxes = len(data['level'])
    for i in range(boxes ):
        (x, y, w, h) = (data['left'][i], data['top'][i], data['width'][i], data['height'][i])
        #Draw box        
        cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
    

    【讨论】:

      【解决方案2】:

      使用 pytesseract 似乎不是获得该职位的最佳主意,但您可以这样做:

      from pytesseract import pytesseract
      pytesseract.run_tesseract('image.png', 'output', lang=None, boxes=False, config="hocr")
      

      【讨论】:

      【解决方案3】:

      您可以使用下面的脚本将每个字符保存为图像,这适用于 python 3.6+

      import cv2
      import pytesseract 
      import numpy
      import time
      from PIL import ImageGrab
      
      path_to_save = "img_out/"
      img = cv2.imread("image_INAUTXQ_www.facebook.com.png")
      img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
      
      hImg, wImg,_ = img.shape
      boxes = pytesseract.image_to_boxes(img)
      ROI_number=0
      for b in boxes.splitlines():
          b = b.split(' ')
          x, y, w, h = int(b[1]), int(b[2]), int(b[3]), int(b[4])
          # cv2.rectangle(img, (x,hImg- y), (w,hImg- h), (50, 50, 255), 1)
          x1,y1=hImg-h,hImg-y
          x2,y2=x,w
          roi=img[x1:y1,x2:y2]
          output = cv2.resize(roi,(300,300))
          # cv2.imshow('roi', roi)
          # cv2.imshow('img',img)
          # cv2.waitKey(0)
          cv2.imwrite("test"+str(ROI_number)+".jpeg",output)
          ROI_number+=1
      

      【讨论】:

        【解决方案4】:

        字符的位置可以找到如下。

        import csv
        import cv2
        from pytesseract import pytesseract as pt
        
        pt.run_tesseract('bw.png', 'output', lang=None, boxes=True, config="hocr")
        
        # To read the coordinates
        boxes = []
        with open('output.box', 'rb') as f:
            reader = csv.reader(f, delimiter = ' ')
            for row in reader:
                if(len(row)==6):
                    boxes.append(row)
        
        # Draw the bounding box
        img = cv2.imread('bw.png')
        h, w, _ = img.shape
        for b in boxes:
            img = cv2.rectangle(img,(int(b[1]),h-int(b[2])),(int(b[3]),h-int(b[4])),(255,0,0),2)
        
        cv2.imshow('output',img)
        

        使用此方法时,可能会漏掉一些文本。它需要对图像进行一些预处理(即背景减法)以获得更好的结果。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-02-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-04-30
          • 2022-01-15
          • 1970-01-01
          相关资源
          最近更新 更多