6

I try to display the image located here: http://skyservice.pha.jhu.edu/DR12/ImgCutout/getjpeg.aspx?ra=118.70299999999999&dec=45.721000000000004&width=10&height=10&scale=0.6

The image looks like this:

enter image description here

I use this code:

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)

And it displays this:

enter image description here

Where all colours are too blue. I have tried various possibilities to change cv2.IMREAD_COLOR with values found in the manual, on StackOverflow or elsewhere on the net, like -1, 0, 1, cv2.COLOR_BGR2RGB, ... but I haven't been able to get the right colours. I have tried cv2.COLOR_BGR2GRAY, it didn't even show in gray scales. I even tried this answer, but cv2.CV_LOAD_IMAGE_COLORdoesn't seem to exist anymore...

Is there a correct value of cv2.imdecode() flag, or a special colormap of plt.imshow(), which would give me the initial colours?

Community
  • 1
  • 1
Matt
  • 763
  • 1
  • 7
  • 25
  • 2
    `matplotlib` requires RGB ordering whereas OpenCV (perversely) uses `BGR`. I think you need to use `cv2.cvtColor()` to convert between the two. – Mark Setchell Sep 25 '18 at 09:21
  • Great!!! I wasn't aware of that! Cheers mate. it works. I post a reply thanks to your answer right now. :) – Matt Sep 25 '18 at 09:38

1 Answers1

16

Thanks to Mark Setchell, it now works. I quote him:

matplotlib requires RGB ordering whereas OpenCV (perversely) uses BGR

Therefore, the correct code is

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
Matt
  • 763
  • 1
  • 7
  • 25
  • Interesting! I guess this just affect displaying, if I train a model use `BGR`, there will be no difference, right? – Vimos Nov 06 '19 at 03:21
  • I suppose not. But if you want to display it properly using OpenCV, be careful with colour coding. :) – Matt Nov 06 '19 at 10:55
  • @Vimos If you train a network with RGB images and give it a BGR then you can definitely expect worse accuracy. Same if you do the opposite (train with BGR images and give it an RGB image). – Arthur Tacca Dec 19 '19 at 15:39