如何使用 OpenCV 读取给定 link 的图像,然后使用 plt.imshow() 绘制它?
How do I read an image given its link using OpenCV and then plot it using plt.imshow()?
我试过了
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).
当我做的时候
plt.imshow(img)
报错
Image data of dtype object cannot be converted to float
我想你在阅读之前忘记将下载的图像图像文件保存到磁盘。
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)
如果你想直接显示图片,不保存到磁盘,使用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()
不确定我会引入 PIL 作为附加依赖项以及 OpenCV,也不会将图像写入磁盘。
我觉得这样更直接:
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)
我试过了
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).
当我做的时候
plt.imshow(img)
报错
Image data of dtype object cannot be converted to float
我想你在阅读之前忘记将下载的图像图像文件保存到磁盘。
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)
如果你想直接显示图片,不保存到磁盘,使用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()
不确定我会引入 PIL 作为附加依赖项以及 OpenCV,也不会将图像写入磁盘。
我觉得这样更直接:
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)