1

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

1
  • cv2.VideoCapture should work. Or download the file to a temp folder and open with imread Commented Jan 15, 2021 at 21:08

2 Answers 2

3

urllib.request.urlopen() is the proper way to download media when working with opencv-python.

import cv2
import urllib.request
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"
url_response = urllib.request.urlopen(url)
img = cv2.imdecode(np.array(bytearray(url_response.read()), dtype=np.uint8), -1)

Sign up to request clarification or add additional context in comments.

1 Comment

This is the only method that worked for me and properly preserved the original image colors.
2

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()

1 Comment

I got the second method to work, thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.