可以对字节图像进行pyteserract吗?

2024-04-19 16:28:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用cv2裁剪图像(将其转换为字节文件,因此不需要保存),然后执行pytesseract

这样我就不需要在这个过程中保存两次图像

  1. 首先,当我创建图像时
  2. 裁剪图像时

过程

## CROPPING THE IMAGE REGION

ys, xs = np.nonzero(mask2)
ymin, ymax = ys.min(), ys.max()
xmin, xmax = xs.min(), xs.max()

croped = image[ymin:ymax, xmin:xmax]


pts = np.int32([[xmin, ymin],[xmin,ymax],[xmax,ymax],[xmax,ymin]])
cv2.drawContours(image, [pts], -1, (0,255,0), 1, cv2.LINE_AA)
#OPENCV IMAGE TO BYTES WITHOUT SAVING TO DISK

is_success, im_buf_arr = cv2.imencode(".jpg", croped)
byte_im = im_buf_arr.tobytes()
#PYTESSERACT IMAGE USING A BYTES FILE

Results = pytesseract.image_to_string(byte_im, lang="eng")
print(Results)

不幸的是,我得到了错误:不支持的图像对象

我错过什么了吗?有没有一种方法可以在剪切时不需要保存文件就完成此过程?非常感谢您的帮助


Tags: 文件图像image过程npcv2xminymax
3条回答

您有croped,它是一个numpy数组

根据pytesseract examples,您只需执行以下操作:

# tesseract needs the right channel order
cropped_rgb = cv2.cvtColor(croped, cv2.COLOR_BGR2RGB)

# give the numpy array directly to pytesseract, no PIL or other acrobatics necessary
Results = pytesseract.image_to_string(cropped_rgb, lang="eng")

from PIL import Image

img_tesseract = Image.fromarray(croped)
Results = pytesseract.image_to_string(img_tesseract, lang="eng")
from PIL import Image
import io
def bytes_to_image(image_bytes):
    io_bytes = io.BytesIO(image_bytes)
    return Image.open(io_bytes)
pytesseract.image_to_data(byte_array_image,lang='eng')

相关问题 更多 >