gpt4 book ai didi

python - 如何使用 OpenCV 交换图像中的蓝色和红色 channel

转载 作者:太空狗 更新时间:2023-10-29 22:21:29 25 4
gpt4 key购买 nike

我在交换图像的 channel (特别是红色和蓝色)时遇到了一些问题。我正在使用 Opencv 3.0.0 和 Python 2.7.12。以下是我交换 channel 的代码

import cv2

img = cv2.imread("input/car1.jpg")

#The obvious approach
Cimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

#Manual Approach
red = img[:,:,2]
blue = img[:,:,0]

img[:,:,0] = red
img[:,:,2] = blue

cv2.imshow("frame",Cimg)
cv2.imshow("frame2", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

我无法弄清楚为什么经过相同(可能)操作的相同图像会给出两个不同的输出。有人可以说明问题出在哪里吗?

原始图像 The original Image

手动操作 The manual operation

COLOR_BGR2RGB The cv2.COLOR_BGR2RGB operation

最佳答案

redblue 只是图像的 View 。当你执行 img[:,:,0] = red 这会改变 img 也会改变 blue 这只是一个 View (基本上只是一个引用到子数组 img[:,:,0]) 而不是副本,因此您丢失了原始的蓝色 channel 值。基本上,您假设的是临时副本,但事实并非如此。添加 .copy() 即可。

img = np.arange(27).reshape((3,3,3))

red = img[:,:,2].copy()
blue = img[:,:,0].copy()

img[:,:,0] = red
img[:,:,2] = blue

print("with copy:\n", img)

img = np.arange(27).reshape((3,3,3))

red = img[:,:,2]
blue = img[:,:,0]

img[:,:,0] = red
img[:,:,2] = blue

print("without copy:\n",img)

结果:

复制:

 [[[ 2  1  0]
[ 5 4 3]
[ 8 7 6]]

[[11 10 9]
[14 13 12]
[17 16 15]]

[[20 19 18]
[23 22 21]
[26 25 24]]]

无文案:

 [[[ 2  1  2]
[ 5 4 5]
[ 8 7 8]]

[[11 10 11]
[14 13 14]
[17 16 17]]

[[20 19 20]
[23 22 23]
[26 25 26]]]

注意:您实际上只需要 1 个 channel 的 1 个临时副本。或者你也可以简单地做 img[:,:,::-1] 这将再次创建一个 View 但是交换 channel ,img 将保持不变,除非你重新分配它:

img = np.arange(27).reshape((3,3,3))

print(img[:,:,::-1])
print(img)
img = img[:,:,::-1]
print(img)

结果:

[[[ 2  1  0]
[ 5 4 3]
[ 8 7 6]]

[[11 10 9]
[14 13 12]
[17 16 15]]

[[20 19 18]
[23 22 21]
[26 25 24]]]


[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]]

[[ 9 10 11]
[12 13 14]
[15 16 17]]

[[18 19 20]
[21 22 23]
[24 25 26]]]


[[[ 2 1 0]
[ 5 4 3]
[ 8 7 6]]

[[11 10 9]
[14 13 12]
[17 16 15]]

[[20 19 18]
[23 22 21]
[26 25 24]]]

关于python - 如何使用 OpenCV 交换图像中的蓝色和红色 channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38538952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com