python-3.x - cv2.imdecode (python opencv) 颜色错误

标签 python-3.x opencv cv2

我尝试显示位于此处的图像:http://skyservice.pha.jhu.edu/DR12/ImgCutout/getjpeg.aspx?ra=118.70299999999999&dec=45.721000000000004&width=10&height=10&scale=0.6

图像看起来像这样:

enter image description here

我使用这段代码:

import matplotlib.pyplot as plt
import numpy as np
import urllib
import cv2

url = 'http://skyservice.pha.jhu.edu/DR12/ImgCutout/getjpeg.aspx?ra=118.70299999999999&dec=45.721000000000004&width=10&height=10&scale=0.6'

def url_to_image(url):
    resp = urllib.request.urlopen(url)
    image = np.asarray(bytearray(resp.read()), dtype="uint8")
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    return image

img = url_to_image(url)
plt.imshow(img)

它显示这个:

enter image description here

所有颜色都太蓝了。我已经尝试了各种可能性来更改 cv2.IMREAD_COLOR,使用手册、StackOverflow 或网络上其他地方找到的值,例如 -1、0、1、cv2.COLOR_BGR2RGB , ... 但我无法获得正确的颜色。我试过 cv2.COLOR_BGR2GRAY,它甚至没有以灰度显示。我什至试过this answer , 但是 cv2.CV_LOAD_IMAGE_COLOR 似乎不存在了...

是否有 cv2.imdecode() 标志的正确值,或 plt.imshow() 的特殊颜色图,它会给我初始颜色?

最佳答案

感谢 Mark Setchell,它现在可以工作了。我引用他的话:

matplotlib requires RGB ordering whereas OpenCV (perversely) uses BGR

因此,正确的代码是

def url_to_image(url):
    resp = urllib.request.urlopen(url)
    image = np.asarray(bytearray(resp.read()), dtype="uint8")
    imageBGR = cv2.imdecode(image, cv2.IMREAD_COLOR)
    imageRGB = cv2.cvtColor(imageBGR , cv2.COLOR_BGR2RGB)
    return image

关于python-3.x - cv2.imdecode (python opencv) 颜色错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52494592/

相关文章:

python - 为什么 cv2.medianBlur 返回格式错误?

python-3.x - 使用 Gensim 进行动态主题建模/哪个代码?

mysql - ImportError:没有使用Python3的名为mysql.connector的模块?

python - 如何在某些索引处反转和连接字符串?

c++ - 如何在 opencv 中进行 Mul 混合

opencv - 罗技 Brio OpenCV 捕获设置

matlab - 校准图像以获得位于同一平面上的点的俯 View

python-3.x - CV2 无法连接到 X 服务器 :

python - 列表中每个整数的数字总和

python - 捕获图片的cv2分辨率