How to create png image file-object from numpy array in python without saving to disk (for http request)
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I need to submit PNG-images to a blackbox server with a http request. I use python3 to generate images in a numpy 64x64x3 array. What I currently do is:
- Generate image
- Save image with scipy.misc.toimage to disk
- Open saved image file from disk
- Use requests module to send http requests with the image opened image file object in it
This works perfectly fine, but I want to get rid of step 2 and 3, so I do not need to save my object to disk first and then load it again. Instead I would like to convert my numpy array in a file-object that is compatible with the http server and send it directly. (Like one you get from open() )
I know it is easy to convert from numpy array to PNG-image with PIL for example, but I only find how to do that combined with saving to disk in one function.
Thank you very much for any help!
This is my code so far:
import numpy as np
import requests
from scipy.misc import toimage
arr = generate64x64x3ImageWithNumpy()
toimage(arr, cmin=0.0, cmax=255.0).save('tmp.png')
d = 'key':API_KEY
f= 'image': open('tmp.png', 'rb')
result = requests.post(SERVER_URL, files=f, data=d)
I want this:
arr = generate64x64x3ImageWithNumpy()
not_on_disk = numpyArrayToPNGImageWithoutSavingOnDisk(arr)
d = 'key':API_KEY
f = 'image': not_on_disk
result = requests.post(SERVER_URL, files=f, data=d)
python numpy http request png
add a comment |
I need to submit PNG-images to a blackbox server with a http request. I use python3 to generate images in a numpy 64x64x3 array. What I currently do is:
- Generate image
- Save image with scipy.misc.toimage to disk
- Open saved image file from disk
- Use requests module to send http requests with the image opened image file object in it
This works perfectly fine, but I want to get rid of step 2 and 3, so I do not need to save my object to disk first and then load it again. Instead I would like to convert my numpy array in a file-object that is compatible with the http server and send it directly. (Like one you get from open() )
I know it is easy to convert from numpy array to PNG-image with PIL for example, but I only find how to do that combined with saving to disk in one function.
Thank you very much for any help!
This is my code so far:
import numpy as np
import requests
from scipy.misc import toimage
arr = generate64x64x3ImageWithNumpy()
toimage(arr, cmin=0.0, cmax=255.0).save('tmp.png')
d = 'key':API_KEY
f= 'image': open('tmp.png', 'rb')
result = requests.post(SERVER_URL, files=f, data=d)
I want this:
arr = generate64x64x3ImageWithNumpy()
not_on_disk = numpyArrayToPNGImageWithoutSavingOnDisk(arr)
d = 'key':API_KEY
f = 'image': not_on_disk
result = requests.post(SERVER_URL, files=f, data=d)
python numpy http request png
add a comment |
I need to submit PNG-images to a blackbox server with a http request. I use python3 to generate images in a numpy 64x64x3 array. What I currently do is:
- Generate image
- Save image with scipy.misc.toimage to disk
- Open saved image file from disk
- Use requests module to send http requests with the image opened image file object in it
This works perfectly fine, but I want to get rid of step 2 and 3, so I do not need to save my object to disk first and then load it again. Instead I would like to convert my numpy array in a file-object that is compatible with the http server and send it directly. (Like one you get from open() )
I know it is easy to convert from numpy array to PNG-image with PIL for example, but I only find how to do that combined with saving to disk in one function.
Thank you very much for any help!
This is my code so far:
import numpy as np
import requests
from scipy.misc import toimage
arr = generate64x64x3ImageWithNumpy()
toimage(arr, cmin=0.0, cmax=255.0).save('tmp.png')
d = 'key':API_KEY
f= 'image': open('tmp.png', 'rb')
result = requests.post(SERVER_URL, files=f, data=d)
I want this:
arr = generate64x64x3ImageWithNumpy()
not_on_disk = numpyArrayToPNGImageWithoutSavingOnDisk(arr)
d = 'key':API_KEY
f = 'image': not_on_disk
result = requests.post(SERVER_URL, files=f, data=d)
python numpy http request png
I need to submit PNG-images to a blackbox server with a http request. I use python3 to generate images in a numpy 64x64x3 array. What I currently do is:
- Generate image
- Save image with scipy.misc.toimage to disk
- Open saved image file from disk
- Use requests module to send http requests with the image opened image file object in it
This works perfectly fine, but I want to get rid of step 2 and 3, so I do not need to save my object to disk first and then load it again. Instead I would like to convert my numpy array in a file-object that is compatible with the http server and send it directly. (Like one you get from open() )
I know it is easy to convert from numpy array to PNG-image with PIL for example, but I only find how to do that combined with saving to disk in one function.
Thank you very much for any help!
This is my code so far:
import numpy as np
import requests
from scipy.misc import toimage
arr = generate64x64x3ImageWithNumpy()
toimage(arr, cmin=0.0, cmax=255.0).save('tmp.png')
d = 'key':API_KEY
f= 'image': open('tmp.png', 'rb')
result = requests.post(SERVER_URL, files=f, data=d)
I want this:
arr = generate64x64x3ImageWithNumpy()
not_on_disk = numpyArrayToPNGImageWithoutSavingOnDisk(arr)
d = 'key':API_KEY
f = 'image': not_on_disk
result = requests.post(SERVER_URL, files=f, data=d)
python numpy http request png
python numpy http request png
asked Nov 16 '18 at 14:03
jobuschjobusch
112
112
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
You can use an in memory iostream with savefig (https://docs.python.org/3/library/io.html#io.BytesIO)
import io
tmpFile = io.BytesIO()
savefig(tmpFile, format='png')
To verify that this worked tmpFile
can be compared with the actual file as saved to disk.
# Get contents of tmpFile
tmpFile.seek(0)
not_on_disk = tmpFile.read(-1)
# Save to and load from disk
fname = 'tmp.png'
savefig(fname)
on_disk = open(fname, 'rb').read(-1)
>>>not_on_disk == on_disk
True
Edit You're looking at using scipy and pil rather than matplotlib but the answer should work the same, including the format
keyword for saving.
Thank you very much for your fast response! :) But what variable do I need to pass to my http request? Is it tmpFile or not_on_disk? with open(...) I have type _io.BufferedReader, so this is what I want. tmpFile is of type BytesIO and not_on_disk is of type _bytes. Any way to convert? Also if I try to open not_on_disk I get "embedded null byte"-error. If I use PIL to open I get PngImageFile object has no attribute read when I make the request. Sorry for my little understanding.
– jobusch
Nov 16 '18 at 17:52
It looks like therequests.post
takes a file handle, so you would want to passtmpFile
(after callingtmpFile.seek(0)
to set the beginning of the file).
– user2699
Nov 16 '18 at 19:14
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53339373%2fhow-to-create-png-image-file-object-from-numpy-array-in-python-without-saving-to%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can use an in memory iostream with savefig (https://docs.python.org/3/library/io.html#io.BytesIO)
import io
tmpFile = io.BytesIO()
savefig(tmpFile, format='png')
To verify that this worked tmpFile
can be compared with the actual file as saved to disk.
# Get contents of tmpFile
tmpFile.seek(0)
not_on_disk = tmpFile.read(-1)
# Save to and load from disk
fname = 'tmp.png'
savefig(fname)
on_disk = open(fname, 'rb').read(-1)
>>>not_on_disk == on_disk
True
Edit You're looking at using scipy and pil rather than matplotlib but the answer should work the same, including the format
keyword for saving.
Thank you very much for your fast response! :) But what variable do I need to pass to my http request? Is it tmpFile or not_on_disk? with open(...) I have type _io.BufferedReader, so this is what I want. tmpFile is of type BytesIO and not_on_disk is of type _bytes. Any way to convert? Also if I try to open not_on_disk I get "embedded null byte"-error. If I use PIL to open I get PngImageFile object has no attribute read when I make the request. Sorry for my little understanding.
– jobusch
Nov 16 '18 at 17:52
It looks like therequests.post
takes a file handle, so you would want to passtmpFile
(after callingtmpFile.seek(0)
to set the beginning of the file).
– user2699
Nov 16 '18 at 19:14
add a comment |
You can use an in memory iostream with savefig (https://docs.python.org/3/library/io.html#io.BytesIO)
import io
tmpFile = io.BytesIO()
savefig(tmpFile, format='png')
To verify that this worked tmpFile
can be compared with the actual file as saved to disk.
# Get contents of tmpFile
tmpFile.seek(0)
not_on_disk = tmpFile.read(-1)
# Save to and load from disk
fname = 'tmp.png'
savefig(fname)
on_disk = open(fname, 'rb').read(-1)
>>>not_on_disk == on_disk
True
Edit You're looking at using scipy and pil rather than matplotlib but the answer should work the same, including the format
keyword for saving.
Thank you very much for your fast response! :) But what variable do I need to pass to my http request? Is it tmpFile or not_on_disk? with open(...) I have type _io.BufferedReader, so this is what I want. tmpFile is of type BytesIO and not_on_disk is of type _bytes. Any way to convert? Also if I try to open not_on_disk I get "embedded null byte"-error. If I use PIL to open I get PngImageFile object has no attribute read when I make the request. Sorry for my little understanding.
– jobusch
Nov 16 '18 at 17:52
It looks like therequests.post
takes a file handle, so you would want to passtmpFile
(after callingtmpFile.seek(0)
to set the beginning of the file).
– user2699
Nov 16 '18 at 19:14
add a comment |
You can use an in memory iostream with savefig (https://docs.python.org/3/library/io.html#io.BytesIO)
import io
tmpFile = io.BytesIO()
savefig(tmpFile, format='png')
To verify that this worked tmpFile
can be compared with the actual file as saved to disk.
# Get contents of tmpFile
tmpFile.seek(0)
not_on_disk = tmpFile.read(-1)
# Save to and load from disk
fname = 'tmp.png'
savefig(fname)
on_disk = open(fname, 'rb').read(-1)
>>>not_on_disk == on_disk
True
Edit You're looking at using scipy and pil rather than matplotlib but the answer should work the same, including the format
keyword for saving.
You can use an in memory iostream with savefig (https://docs.python.org/3/library/io.html#io.BytesIO)
import io
tmpFile = io.BytesIO()
savefig(tmpFile, format='png')
To verify that this worked tmpFile
can be compared with the actual file as saved to disk.
# Get contents of tmpFile
tmpFile.seek(0)
not_on_disk = tmpFile.read(-1)
# Save to and load from disk
fname = 'tmp.png'
savefig(fname)
on_disk = open(fname, 'rb').read(-1)
>>>not_on_disk == on_disk
True
Edit You're looking at using scipy and pil rather than matplotlib but the answer should work the same, including the format
keyword for saving.
edited Nov 16 '18 at 14:50
answered Nov 16 '18 at 14:40
user2699user2699
1,449720
1,449720
Thank you very much for your fast response! :) But what variable do I need to pass to my http request? Is it tmpFile or not_on_disk? with open(...) I have type _io.BufferedReader, so this is what I want. tmpFile is of type BytesIO and not_on_disk is of type _bytes. Any way to convert? Also if I try to open not_on_disk I get "embedded null byte"-error. If I use PIL to open I get PngImageFile object has no attribute read when I make the request. Sorry for my little understanding.
– jobusch
Nov 16 '18 at 17:52
It looks like therequests.post
takes a file handle, so you would want to passtmpFile
(after callingtmpFile.seek(0)
to set the beginning of the file).
– user2699
Nov 16 '18 at 19:14
add a comment |
Thank you very much for your fast response! :) But what variable do I need to pass to my http request? Is it tmpFile or not_on_disk? with open(...) I have type _io.BufferedReader, so this is what I want. tmpFile is of type BytesIO and not_on_disk is of type _bytes. Any way to convert? Also if I try to open not_on_disk I get "embedded null byte"-error. If I use PIL to open I get PngImageFile object has no attribute read when I make the request. Sorry for my little understanding.
– jobusch
Nov 16 '18 at 17:52
It looks like therequests.post
takes a file handle, so you would want to passtmpFile
(after callingtmpFile.seek(0)
to set the beginning of the file).
– user2699
Nov 16 '18 at 19:14
Thank you very much for your fast response! :) But what variable do I need to pass to my http request? Is it tmpFile or not_on_disk? with open(...) I have type _io.BufferedReader, so this is what I want. tmpFile is of type BytesIO and not_on_disk is of type _bytes. Any way to convert? Also if I try to open not_on_disk I get "embedded null byte"-error. If I use PIL to open I get PngImageFile object has no attribute read when I make the request. Sorry for my little understanding.
– jobusch
Nov 16 '18 at 17:52
Thank you very much for your fast response! :) But what variable do I need to pass to my http request? Is it tmpFile or not_on_disk? with open(...) I have type _io.BufferedReader, so this is what I want. tmpFile is of type BytesIO and not_on_disk is of type _bytes. Any way to convert? Also if I try to open not_on_disk I get "embedded null byte"-error. If I use PIL to open I get PngImageFile object has no attribute read when I make the request. Sorry for my little understanding.
– jobusch
Nov 16 '18 at 17:52
It looks like the
requests.post
takes a file handle, so you would want to pass tmpFile
(after calling tmpFile.seek(0)
to set the beginning of the file).– user2699
Nov 16 '18 at 19:14
It looks like the
requests.post
takes a file handle, so you would want to pass tmpFile
(after calling tmpFile.seek(0)
to set the beginning of the file).– user2699
Nov 16 '18 at 19:14
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53339373%2fhow-to-create-png-image-file-object-from-numpy-array-in-python-without-saving-to%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown