我有一张颜色以BGR编码的图片。如何以高效的方式将每个像素的B和R元素交换,从而转换我的PIL图片?
我有一张颜色以BGR编码的图片。如何以高效的方式将每个像素的B和R元素交换,从而转换我的PIL图片?
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()
。
img = img[:,:, [2, 1, 0, 3]]
按照您的喜好切换频道!
# 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]]