Tesseract is an open-source OCR engine, and pytesseract calls it from Python. This page builds an OCR connector on them (see OCR usage basics for what a connector is).
Install Tesseract
Install the Tesseract program, then the two Python packages:
Add the Tesseract folder (C:\Program Files\Tesseract-OCR) to PATH, or set pytesseract.pytesseract.tesseract_cmd to the full path of tesseract.exe.
The connector
pytesseract.image_to_data() returns every word it recognized with its position and the block, paragraph and line it belongs to. The connector joins the words of each line into one TextFragment whose rectangle covers the line:
importioimportpytesseractfromPILimportImagefromgroupdocs.redactionimportRedactorfromgroupdocs.redaction.integration.ocrimportRecognizedImage,TextFragment,TextLinefromgroupdocs.redaction.optionsimportLoadOptions,RedactorSettings,SaveOptionsfromgroupdocs.redaction.options.drawingimportColor,Rectanglefromgroupdocs.redaction.redactionsimportExactPhraseRedaction,ReplacementOptionsclassTesseractOcrConnector(object):"""Recognizes text with Tesseract and reports each line as one fragment."""defrecognize(self,image_stream):image=Image.open(io.BytesIO(image_stream.read()))data=pytesseract.image_to_data(image,output_type=pytesseract.Output.DICT)lines={}order=[]fori,wordinenumerate(data["text"]):ifnotword.strip():continuekey=(data["block_num"][i],data["par_num"][i],data["line_num"][i])ifkeynotinlines:lines[key]=[]order.append(key)lines[key].append(i)ifnotorder:returnNonerecognized=[]forkeyinorder:words=lines[key]left=min(data["left"][i]foriinwords)top=min(data["top"][i]foriinwords)right=max(data["left"][i]+data["width"][i]foriinwords)bottom=max(data["top"][i]+data["height"][i]foriinwords)text=" ".join(data["text"][i]foriinwords)rectangle=Rectangle(left,top,right-left,bottom-top)recognized.append(TextLine([TextFragment(text,rectangle)]))returnRecognizedImage(recognized)defuse_tesseract_ocr():settings=RedactorSettings(TesseractOcrConnector())withRedactor("./scan.png",LoadOptions(),settings)asredactor:result=redactor.apply(ExactPhraseRedaction("Emily Johnson",ReplacementOptions(Color.black)))print("Status: "+result.status.name)options=SaveOptions()options.add_suffix=Trueoptions.rasterize_to_pdf=False# keep the PNG formatresult_path=redactor.save(options)print("Output saved to "+result_path)if__name__=="__main__":use_tesseract_ocr()
scan.png is the sample file used in this example. Click here to download it.
Each line is one fragment because GroupDocs.Redaction 26.10 covers a match inside a fragment and reports a match that spans two fragments as APPLIED without covering it. Inside a fragment, the box is placed by the match’s character position, so near the end of a long line it can fall a few pixels short: on a 683-pixel line of text, the box over the last two words stopped 10 pixels before the last letter. On this page’s sample, “Emily Johnson” in a 338-pixel line, the box covers the name. Check the output, or report shorter fragments, as long as each phrase you redact fits in one.
The same connector redacts the text of images embedded in a PDF or a Word document: open that document instead of the image.
Was this page helpful?
Any additional feedback you'd like to share with us?
Please tell us how we can improve this page.
Thank you for your feedback!
We value your opinion. Your feedback will help us improve our documentation.