An OCR connector is an object with a recognize(image_stream) method, or a function that takes image_stream:
image_stream is the image to recognize, valid during the call. image_stream.read() gives its bytes.
It returns a RecognizedImage, or None for an image with no text.
A RecognizedImage holds the lines of text, each a TextLine of TextFragment objects. A fragment is a piece of text with the rectangle, in pixels from the image’s top-left corner, where it was found. Report each line as one fragment: its text and the rectangle that covers it.
GroupDocs.Redaction searches the recognized text for the redaction’s phrase or expression. It covers a match inside a fragment, placing the box by the match’s position in the fragment’s text. A match that spans two fragments is reported APPLIED but not covered (GroupDocs.Redaction 26.10), which is why a line is one fragment. An exception the connector raises reaches the caller of apply().
A connector without an OCR engine
The connector below stands in for an OCR engine: for every image, it reports the line “Customer: Emily Johnson” where it is in the sample scan. It shows the shapes a real connector returns, and it runs without any OCR software:
fromgroupdocs.redactionimportRedactorfromgroupdocs.redaction.integration.ocrimportRecognizedImage,TextFragment,TextLinefromgroupdocs.redaction.optionsimportLoadOptions,RedactorSettings,SaveOptionsfromgroupdocs.redaction.options.drawingimportColor,Rectanglefromgroupdocs.redaction.redactionsimportExactPhraseRedaction,ReplacementOptionsclassFixedResultOcrConnector(object):"""Reports the line "Customer: Emily Johnson" at the same place in every image."""def__init__(self):self.images=0defrecognize(self,image_stream):self.images+=1image_bytes=image_stream.read()# what a real OCR engine would read# One fragment per line: its text and the rectangle that covers it, in pixelsline=TextLine([TextFragment("Customer: Emily Johnson",Rectangle(122,365,338,28))])returnRecognizedImage([line])defocr_usage_basics():connector=FixedResultOcrConnector()withRedactor("./scan.png",LoadOptions(),RedactorSettings(connector))asredactor:result=redactor.apply(ExactPhraseRedaction("Emily Johnson",ReplacementOptions(Color.black)))print("Images recognized: %d, status: %s"%(connector.images,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__":ocr_usage_basics()
scan.png is the sample file used in this example. Click here to download it.
RedactorSettings(connector) takes the connector as its only argument. Next to a logger and a redaction callback, pass it by name: RedactorSettings(logger, callback, connector) or RedactorSettings(ocr_connector=connector).