图片由opencv加载错误

时间:2019-03-07 14:24:37

标签: python opencv

灾难! enter image description here

如您所见,图像未正确加载。原本的: enter image description here

代码:

import cv2
import imutils
a=imutils.url_to_image("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png", readFlag=-1)
cv2.imshow("goog", a)
cv2.waitKey()

在imutils中实现url_to_image:

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

我还尝试了readFlag = cv2.IMREAD_UNCHANGED,但这也没有解决问题。

请发送帮助

2 个答案:

答案 0 :(得分:0)

好帮派,我们做到了

所以我尝试了另一种显示方式:

plt.figure("Correct")
plt.imshow(imutils.opencv2matplotlib(a))
plt.show()

enter image description here

不会出现运气。但是,然后查看opencv2matplotlib源,我们发现:

def opencv2matplotlib(image):
    # OpenCV represents images in BGR order; however, Matplotlib
    # expects the image in RGB order, so simply convert from BGR
    # to RGB and return
    return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

啊哈,但是我们有4个通道的颜色(alpha),所以从常识上讲我们需要cv2.COLOR_BGRA2RGBA而不是cv2.COLOR_BGR2RGB !!

检验这一理论:

plt.figure("Correct")
plt.imshow(cv2.cvtColor(a, cv2.COLOR_BGRA2RGBA))
plt.show()

我们得到...

enter image description here

呜呼嘘声!

答案 1 :(得分:0)

# import the necessary packages
import numpy as np
import urllib
import cv2

def url_to_image(url):
    # download the image, convert it to a NumPy array, and then read
    # it into OpenCV format
    resp = urllib.request.urlopen(url)
    image = np.asarray(bytearray(resp.read()), dtype="uint8")
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)

    # return the image
    return image


# initialize the list of image URLs to download
url="http://i.dailymail.co.uk/i/pix/2015/09/01/18/2BE1E88B00000578-3218613-image-m-5_1441127035222.jpg"

print ("downloading %s" % (url))
image = url_to_image(url)
cv2.imshow("Image", image)
cv2.waitKey(0)

输出为: the image displayed fetched from the given url