问题
将图像加载到 Python 中(如下所示),我如何知道 channel 的顺序? (例如 BGR 或 RGB)
代码
from PIL import Image
import numpy as np
image_pil = Image.open("Stonehenge.jpg")
image_np = np.array(image_pil)
image_np[0][0]
结果
array([ 52, 123, 155], dtype=uint8)
具体问题
我如何知道 52
对应的是红色 channel 、蓝色 channel 还是其他 channel ?还是这个问题在概念层面上没有意义?
注意事项
在针对 Java 而不是 Python 的类似问题中,one person claims :
If you are reading in the image file, or you have access to the code that reads in the file, know it is:
- BGR order if you used cv2.imread(),
- RGB order if you used mpimg.imread(), (assuming import matplotlib.image as mpimg)
If you don't know how the file was opened, the accepted answer BufferedImage is great for Java.
最佳答案
因为您使用 PIL
并且您没有指定任何其他模式来加载图像,所以您得到 R G B。
您可以通过检查 Image 实例上的“mode”属性来验证这一点:
image_pil.mode # should return the string 'RGB'
Pillow 通过 image_pil.__array_interface__
魔术方法支持数组接口(interface),因此当您创建 ndarray 时,numpy 只使用它。即,它对颜色 channel 顺序一无所知。如果你有一个存储为 BGR 的图像文件,并且你像这样加载它,你将在红色 channel 中获得蓝色数据,反之亦然,当你显示它时它看起来会出错。
关于python - 如何检查图像的 channel 顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46898979/