0

I've tried this

from PIL import Image
import requests

im = Image.open(requests.get('http://images.cocodataset.org/train2017/000000000086.jpg', stream=True).raw)
img = cv.imread('im.jpg')
print(img)

This works but print(img) prints "None". Also, shouldn't it be cv.imread(im)(doing that gives an error).

when i do

plt.imshow(img)

it gives an error

Image data of dtype object cannot be converted to float

Community
  • 1
  • 1

2 Answers2

3

Not sure I would introduce PIL as an additional dependency as well as OpenCV, nor would I write the image to disk.

I think it would be more direct to do:

import cv2
import requests
import numpy as np

# Fetch JPEG data
d = requests.get('http://images.cocodataset.org/train2017/000000000086.jpg')

# Decode in-memory, compressed JPEG into Numpy array
im = cv2.imdecode(np.frombuffer(d.content,np.uint8), cv2.IMREAD_COLOR)
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
1

I think you forgot to save the downloaded image image file to disk before reading it.

from PIL import Image
import requests
import cv2 as cv

im = Image.open(requests.get('http://images.cocodataset.org/train2017/000000000086.jpg', stream=True).raw)

im.save('im.jpg') # write image file to disk

img = cv.imread('im.jpg') # read image file from disk
print(img)

If you want to show image directly, without saving it to disk, use this approach from another answer:

import numpy as np

im = Image.open(...)
img = np.array(im) 
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Convert RGB to BGR 
plt.imshow(img)
plt.show()
Sparkofska
  • 1,280
  • 2
  • 11
  • 34