PIL 旋转图像颜色(BGR -> RGB)

78

我有一张颜色以BGR编码的图片。如何以高效的方式将每个像素的B和R元素交换,从而转换我的PIL图片?

14个回答

2

TLDR: 如果您已经导入了 cv2,请使用 cv2.cvtColor(img, cv2.COLOR_BGR2RGB))


速度比较:

%%timeit
img_ = Image.fromarray(img[...,::-1])
# 5.77 ms ± 12.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%%timeit
img_ = Image.fromarray(img[...,[2,1,0]])
# 6.2 ms ± 2.43 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%%timeit
img_ = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
# 442 µs ± 4.84 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

问题在于,OP询问的是img是否已经处于PIL图像格式,而cv2.cvtColor(img, cv2.COLOR_BGR2RGB))需要img处于numpy数组格式。

但是,cv2.imread()很可能是您得到BGR图像的原因。不是Image.open()


1
如果您有一个alpha频带,请使用此代码:
img = img[:,:, [2, 1, 0, 3]]

0

按照您的喜好切换频道!

# You source order
source = 'BGR'

# The order you want
target = 'RGB'

# Grab the indices of channel in last dimension
image = image[...,[target.index(s) for s in source]]

0

你应该可以使用ImageMath模块完成这个任务。

编辑:

Joe的解决方案更好,我想多了。:)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接