python OCR on macOS

Viewed 147

Below is code I have written that does OCR with pytesseract.

import pyperclip, os, glob, pytesseract
from PIL import Image

all_files = glob.glob('/Users/<user>/Desktop/*') 
filename = max(all_files, key=os.path.getctime)

text = pytesseract.image_to_string(Image.open(filename))
pyperclip.copy(text)

Simple enough, it performs basic ocr to the image specified, the latest image that I have took a screenshot of. What I was wondering is how to put have the ocr'ed text in my clip board. I have looked into the pyperclip library, and a simple pyperclip.copy should do it. I have tried simply copying it, and everywhere says that is correct. Is there something I am missing?

1 Answers

That should work, but if it doesn't you can try pushing it in and out of a file.

import pyperclip, os, glob, pytesseract, shutil
from PIL import Image

all_files = glob.glob('/Users/<user>/Desktop/*') 
filename = max(all_files, key=os.path.getctime)

text = pytesseract.image_to_string(Image.open(filename))

#writes text to file
file = open("/Users/<user>/pyOCR/string.txt","r+") 
file.truncate(0)
file.write(text)
file.close()

#read text from file
with open('/Users/<user>/pyOCR/string.txt') as f:
    lines = f.readlines()
    f.close()

full_text=''
for line in lines: 
    full_text+=line

#copies text
pyperclip.copy(full_text)
Related