问题描述
我有以下代码:
imgs = glob.glob('/home/chipin/heart/tray.png')
current_img = io.imread(imgs[0])
cv2.imwrite('/home/chipin/heart/01.png', current_img[0:511,0:511])
图片尺寸为512 * 512,保存后,蓝色图片变为黄色.似乎一个渠道被放弃了.我真的不知道为什么.
The size of picture is 512*512, after being saved, a blue picture turns yellow. It seems that a channel is abandoned. I really don't know why.
这是current_img的值:
Here is the value of current_img:
推荐答案
您的问题在于 skimage.io.imread
将图像加载为RGB(或RGBA),但是OpenCV假定图像为 BGR或BGRA (BGR是默认的OpenCV颜色格式).这意味着蓝色和红色飞机会翻转.
Your problem is in the fact that skimage.io.imread
loads image as RGB (or RGBA), but OpenCV assumes the image to be BGR or BGRA (BGR is the default OpenCV colour format). This means that blue and red planes get flipped.
让我们使用以下简单的测试图像进行尝试:
Let's try this out with the following simple test image:
首先让我们尝试您的原始算法:
First let's try your original algorithm:
import skimage.io
import cv2
img = skimage.io.imread('sample.png')
cv2.imwrite('sample_out_1.png', img)
我们得到以下结果:
如您所见,红色和蓝色通道被明显地交换了.
As you can see, red and blue channels are visibly swapped.
第一种方法(假设您仍要使用skimage进行读取和cv2进行编写)是使用 cv2.cvtColor
可以将RGB转换为BGR.
The first approach, assuming you want to still use skimage to read and cv2 to write is to use cv2.cvtColor
to convert from RGB to BGR.
由于新的OpenCV文档未提及Python语法,因此在这种情况下,您还可以使用 2.4.x的适当参考.
Since the new OpenCV docs don't mention Python syntax, in this case you can also use the appropriate reference for 2.4.x.
import skimage.io
import cv2
img = skimage.io.imread('sample.png')
cv2.imwrite('sample_out_2.png', cv2.cvtColor(img, cv2.COLOR_RGB2BGR))
现在我们得到以下输出:
Now we get the following output:
一种替代方法是只使用OpenCV -使用 cv2.imread
加载图像.在这种情况下,我们只处理BGR图片.
An alternative is to just use OpenCV -- use cv2.imread
to load the image. In this case we're working only with BGR images.
注意::不提供任何标志意味着默认情况下使用cv2.IMREAD_COLOR
,即,图像始终作为3通道图像加载(删除任何可能的Alpha通道).
NB: Not providing any flags means cv2.IMREAD_COLOR
is used by default -- i.e. image is always loaded as a 3-channel image (dropping any potential alpha channels).
import cv2
img = cv2.imread('sample.png')
cv2.imwrite('sample_out_3.png', img)
从屏幕截图中可以看到,您有一个4通道图像.这将在skimage中表示RGBA,在OpenCV中表示BGRA.原理差不多.
From your screenshot, it appears that you have a 4 channel image. This would mean RGBA in skimage, and BGRA in OpenCV. The principles would be similar.
- 使用颜色转换代码
cv2.COLOR_RGBA2BGRA
- 或将
cv2.imread
与标志cv2.IMREAD_UNCHANGED
一起使用
- Either use colour conversion code
cv2.COLOR_RGBA2BGRA
- Or use
cv2.imread
with flagcv2.IMREAD_UNCHANGED
这篇关于为什么cv2.imwrite()更改图片的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!