简体   繁体   中英

Python: SpooledTemporaryFile suffix not working

I want to write an image using opencv to a temporary file, get the path of that temporary file and pass that path to a function.

import cv2 as cv
from tempfile import NamedTemporaryFile, SpooledTemporaryFile

img = create_my_awesome_image()

with NamedTemporaryFile(suffix=".png") as temp:
    print(temp.name)
    cv.imwrite(temp.name, img) # this one sparks joy

with SpooledTemporaryFile(max_size=1000000, suffix=".png") as temp:
    print(temp.name)
    cv.imwrite(temp.name, img) # this one does not

The first print prints C:\\Users\\FLORIA~1\\AppData\\Local\\Temp\\tmpl2i6nc47.png .
While the second print prints: None .

Using NamedTemporaryFile works perfectly find. However, because the second print prints None, I cannot use the SpooledTemporaryFile together with opencv. Any ideas why the prefix argument of SpooledTemporaryFile is ignored?

The problem is that a spooled file (such as a SpooledTemporaryFile ) doesn't exist on the disk, so it also doesn't have a name.

However, note that cv2.imread() will take a file name as an argument, meaning that it will handle the file opening and it doesn't support spooled files.

If you are only working with png images, they are not encoded, meaning that the variable img already contains the image data in memory and there is nothing else for you to do, just call cv2.imwrite() when you want to save it to the disk. If you want to use a temporary file, it has to be a NamedTemporaryFile .

If you want to handle an encoded image format in memory, such as jpg , you can use cv2.imencode() for that purpose, as in this answer .

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