簡體   English   中英

Python將彩色圖像轉換為白色背景上的黑色文本以進行OCR

[英]Python convert color image to black text on white background for OCR

我有一張需要進行 OCR(光學字符識別)來提取所有數據的圖像。

在此處輸入圖像描述

首先,我想將彩色圖像轉換為白色背景上的黑色文本,以提高 OCR 的准確性。

我嘗試下面的代碼

from PIL import Image
img = Image.open("data7.png")
img.convert("1").save("result.jpg")

它給了我下面不清楚的圖像

在此處輸入圖像描述

我希望有這個圖像

在此處輸入圖像描述

然后,我將使用 pytesseract 獲取數據框

import pytesseract as tess
file = Image.open("data7.png")
text = tess.image_to_data(file,lang="eng",output_type='data.frame')
text

最后,我想得到的數據框如下

在此處輸入圖像描述

由於默認dithering ,使用PIL.Image.convert將 RGB 圖像轉換為二進制圖像會導致“不清楚”圖像。 在您的情況下,您根本不想猶豫:

img.convert("1", dither=Image.Dither.NONE)

會給你一個干凈的轉換:

在此處輸入圖像描述

您仍然需要弄清楚如何以顏色捕獲文本,但是一旦關閉抖動,噪音就消失了。

這是香草枕頭解決方案。 只是對圖像進行灰度化就可以得到很好的結果,但是綠色文本太暗了。

因此,我們首先將綠色通道放大(當然,它可能會剪切,但這不是問題),然后是灰度、反轉和自動對比圖像。

from PIL import Image, ImageOps

img = Image.open('rqDRe.png').convert('RGB')

r, g, b = img.split()

img = Image.merge('RGB', (
    r,
    g.point(lambda i: i * 3),  # brighten green channel
    b,
))

img = ImageOps.autocontrast(ImageOps.invert(ImageOps.grayscale(img)), 5)

img.save('rqDRe_processed.png')

輸出

在此處輸入圖像描述

在使用 Torchvision 測量輸入圖像統計信息時,您可以通過查看最突出的顏色來提取背景顏色。

更具體地說,您可以使用torchvision.transforms.functional.to_tensor

>>> img = Image.open("test.png")
>>> tensor = TF.to_tensor(img)

提取背景顏色:

>>> u, c = tensor.flatten(1).unique(dim=1, return_counts=True)
>>> bckg = u[:,c.argmax()]
tensor([0.1216, 0.1216, 0.1216])

獲取背景掩碼:

>>> mask = (tensor.permute(1,2,0) == bckg).all(dim=-1)

使用torchvision.transforms.functional.to_pil_image轉換回 PIL

>>> res = TF.to_pil_image(mask.float())

在此處輸入圖像描述

然后您可以使用Python tesseract提取數據框:

>>> text = tess.image_to_data(res, lang="eng", output_type='data.frame')

使用from PIL import Image
並將import torchvision.transforms.functional as TF

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM