简体   繁体   中英

Saving files temporarily in Python?

I'd like to save my processed real-time image that I made with PIL to a PNG temporarily for passing it to Tesseract.

As you've probably noticed, this would be an OCR project. I've tried using StringIO and BytesIO but the information that I found wasn't very specific and I'm still not sure how to implement that in my little program.

I'm quite new to Python and to programming in general so please if you land me an anwser be very detailed with your explanation. If there is any better ways to do this, let me know!

Thank you in advance!

import numpy as np
from PIL import ImageGrab
import cv2

def processed_img(image):
    proc_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    proc_img = cv2.adaptiveThreshold(proc_img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
                                     cv2.THRESH_BINARY,11,2)
    return proc_img

def main():
    while(True):
        screen = np.array(ImageGrab.grab([2165, 450, 3020, 740]))
        new_screen = processed_img(screen)
        cv2.imshow('window',new_screen)
        if cv2.waitKey(25) & 0xFF == ord('q'):
            cv2.destroyAllWindows()
            break

main()

io.BytesIO() can be used for that.

You can figure out how to implement it on your own. Here's a sample code

from PIL import Image
from io import BytesIO

img = Image.open(somePath)
... # do other stuff
temp = BytesIO()
img.save(temp)

Then you can use temp.getvalue() to access the binary of the image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM