如何在Python cv2中从Internet URL读取图像?
import cv2.cv as cv
import urllib2
from cStringIO import StringIO
import PIL.Image as pil
url="some_url"
img_file = urllib2.urlopen(url)
im = StringIO(img_file.read())
不好,因为Python向我报告:
TypeError: object.__new__(cStringIO.StringI) is not safe, use cStringIO.StringI.__new__
答案 0 :(得分:22)
由于cv2图像不是字符串(保存Unicode,yucc),而是NumPy数组, - 使用cv2和NumPy来实现它:
import cv2
import urllib
import numpy as np
req = urllib.urlopen('http://answers.opencv.org/upfiles/logo_2.png')
arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
img = cv2.imdecode(arr, -1) # 'Load it as it is'
cv2.imshow('lalala', img)
if cv2.waitKey() & 0xff == 27: quit()
答案 1 :(得分:21)
以下将图像直接读入NumPy数组:
from skimage import io
image = io.imread('https://raw2.github.com/scikit-image/scikit-image.github.com/master/_static/img/logo.png')
答案 2 :(得分:0)
在python3中:
from urllib.request import urlopen
def url_to_image(url, readFlag=cv2.IMREAD_COLOR):
# download the image, convert it to a NumPy array, and then read
# it into OpenCV format
resp = urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, readFlag)
# return the image
return image
这是imutils中url_to_image的实现,因此您可以调用
import imutils
imutils.url_to_image(url)
答案 3 :(得分:0)
如果你正在使用请求,你可以使用这个
from grpc_interceptor import ServerInterceptor.
from grpc_interceptor.exceptions import GrpcException.
import logging.
logger = logging.getLogger()
class ErrorLogger(ServerInterceptor):
def intercept(self, method, request, context, method_name):
try:
return method(request, context)
except Exception() as e:
self.log_error(e)
# context.set_code(e.status_code)
# context.set_details(e.details)
raise
def log_error(self, e: Exception()) -> None:
return logging.exception(e, exc_info=True)
def serve(self):
"""
Starts the gRPC server, and preps
it for serving incoming connections
"""
interceptors = [ErrorLogger()]
server = grpc.server(..., ,interceptors=interceptors)