OpenCV imdecode returns none

I’m trying to read an image from url.

For this, I created the funcion below. For some url I input, it works exactly how I wish, but for others, it doesn’t. In this cases the cv2.imread(img, cv2.IMREAD_COLOR) function returns none.

My code:

import cv2     
from urllib.request import Request, urlopen
import numpy as np

def urlToImage(url):
    # download image,convert to a NumPy array,and read it into opencv
    req = Request(
        headers={'User-Agent': 'Mozilla5.0(Google spider)', 'Range': 'bytes=0-{}'.format(5000)})
    resp = urlopen(req)
    img = np.asarray(bytearray(, dtype="uint8")
    img = cv2.imdecode(img, cv2.IMREAD_COLOR)
    # return the image
    return img

img = urlToImage('https://my_image.jpg')

Example of url that works:


Example of url that doesn’t work:


What i’m doing wrong here?


Seems there is some issue reading the file with urllib but I didn’t dig into.

I tried with import urllib.request as ur instead of from urllib.request import Request, urlopen.

This works for me:

import cv2
import numpy as np
import urllib.request as ur
from matplotlib import pyplot as plt # for testing in Jupyter

def urlToImage(url):
    resp = ur.urlopen(url)
    image = np.asarray(bytearray(, dtype="uint8")
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    return image

Test on Jupyter:

url = ""
im = urlToImage(url)