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(
        url,
        headers={'User-Agent': 'Mozilla5.0(Google spider)', 'Range': 'bytes=0-{}'.format(5000)})
    resp = urlopen(req)
    img = np.asarray(bytearray(resp.read()), dtype="uint8")
    img = cv2.imdecode(img, cv2.IMREAD_COLOR)
    # return the image
    return img

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

Example of url that works:

"https://image.freepik.com/fotos-gratis/paisagem-ambiente-bonito-de-campo-verde_29332-1855.jpg"

Example of url that doesn’t work:

"https://veja.abril.com.br/wp-content/uploads/2019/03/tecnologia-samsung-s10-01.jpg"

What i’m doing wrong here?

Answer

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(resp.read()), dtype="uint8")
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    return image

Test on Jupyter:

url = "https://image.freepik.com/fotos-gratis/paisagem-ambiente-bonito-de-campo-verde_29332-1855.jpg"
im = urlToImage(url)
plt.imshow(im[:,:,::-1])