Search code examples
pythonpython-3.xopencv

OpenCV open image with URL


I keep getting an error when running the code below

import cv2
import urllib3 as urllib
import requests
import numpy as np

url = "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fwallup.net%2Fwp-content%2Fuploads%2F2016%2F03%2F10%2F343179-landscape-nature.jpg"

r = requests.get(url)

imgar = np.array(bytearray(r.text,'utf-8'),dtype=np.uint8)
img = cv2.imdecode(imgar,-1)
cv2.imshow('img',img)
cv2.waitKey()

Error:

cv2.imshow('img',img)
cv2.error: OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-kh7iq4w7\opencv\modules\highgui\src\window.cpp:376: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'

This error keeps happening no matter what I change the photo to and I'm unsure why, thanks


Solution

  • You can try this:

    import urllib.request
    url_response = urllib.request.urlopen(url)
    img_array = np.array(bytearray(url_response.read()), dtype=np.uint8)
    img = cv2.imdecode(img_array, -1)
    cv2.imshow('URL Image', img)
    cv2.waitKey()
    

    An alternative way:

    import cv2
    import urllib3 as urllib
    import requests
    import numpy as np
    import io
    import PIL
    url = "https://s3-us-west-2.amazonaws.com/uw-s3-cdn/wp-content/uploads/sites/6/2017/11/04133712/waterfall-750x500.jpg"
    r = requests.get(url)
    
    response = requests.get(url)
    image_bytes = io.BytesIO(response.content)
    img = PIL.Image.open(image_bytes)
    img.show()