Python OpenCV 在加载时为彩色图像提供错误的颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39316447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:07:58  来源:igfitidea点击:

OpenCV giving wrong color to colored images on loading

pythonimageopencvcolorsrgb

提问by bholagabbar

I'm loading in a color image in Python OpenCV and plotting the same. However, the image I get has it's colors all mixed up.

我正在 Python OpenCV 中加载彩色图像并绘制相同的图像。但是,我得到的图像的颜色都混在一起了。

Here is the code:

这是代码:

import cv2
import numpy as np
from numpy import array, arange, uint8 
from matplotlib import pyplot as plt


img = cv2.imread('lena_caption.png', cv2.IMREAD_COLOR)
bw_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

images = []
images.append(img)
images.append(bw_img)

titles = ['Original Image','BW Image']

for i in xrange(len(images)):
    plt.subplot(1,2,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])

plt.show()

Here is the original image: enter image description here

这是原始图像: enter image description here

And here is the plotted image: enter image description here

这是绘制的图像: enter image description here

回答by TobyD

OpenCV uses BGR as its default colour order for images, matplotlib uses RGB. When you display an image loaded with OpenCv in matplotlib the channels will be back to front.

OpenCV 使用 BGR 作为图像的默认颜色顺序,matplotlib 使用 RGB。当您在 matplotlib 中显示用 OpenCv 加载的图像时,通道将回到前面。

The easiest way of fixing this is to use OpenCV to explicitly convert it back to RGB, much like you do when creating the greyscale image.

解决此问题的最简单方法是使用 OpenCV 将其显式转换回 RGB,就像您在创建灰度图像时所做的那样。

RGB_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

And then use that in your plot.

然后在你的情节中使用它。

回答by okk

As an alternative to the previous answer, you can use (slightly faster)

作为上一个答案的替代方案,您可以使用(稍快)

img = cv2.imread('lena_caption.png')[...,::-1]

img = cv2.imread('lena_caption.png')[...,::-1]

%timeit [cv2.cvtColor(cv2.imread(f), cv2.COLOR_BGR2RGB) for f in files]
231 ms ± 3.08 ms per loop(mean ± std. dev. of 7 runs, 1 loop each)

%timeit [cv2.cvtColor(cv2.imread(f), cv2.COLOR_BGR2RGB) for f in files]
每个循环 231 ms ± 3.08 ms(7 次运行的平均值 ± 标准偏差,每次 1 次循环)

%timeit [cv2.imread(f)[...,::-1] for f in files]
220 ms ± 1.81 ms per loop(mean ± std. dev. of 7 runs, 1 loop each)

%timeit [cv2.imread(f)[...,::-1] for f in files]
每个循环 220 ms ± 1.81 ms(7 次运行的平均值 ± 标准偏差,每次 1 次循环)