cv2.Imshow() 在不同的图像上显示相同的通道颜色

cv2.Imshow() show same channel color on different images

我遇到了一个很奇怪的问题。 Imshow() 为前三个 imshows 显示相同的图像 - 为什么? (只有红色通道,好像把蓝色和绿色调零了) 我正在创建原始图像的副本,但操作似乎会影响所有图像。 第四个 imshow 将红色通道显示为预期的灰度。 我做错了什么?

    ##### Image processing ####
import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread('/home/pi/Documents/testcode_python/Tractor_actual/Pictures/result2.jpg') #reads as BGR
print(img.shape)

no_blue=img
no_green=img
only_red=img[:,:,2] #Takes only red channel from BGR image and saves to "only_red"

no_blue[:,:,0]=np.zeros([img.shape[0], img.shape[1]]) #Puts Zeros on Blue channels for "no_blue"
no_green[:,:,1]=np.zeros([img.shape[0], img.shape[1]])

print(no_blue.shape)

cv2.imshow('Original',img)
cv2.imshow('No Blue',no_blue)
cv2.imshow('No Green',no_green)
cv2.imshow('Only Red', only_red)
cv2.waitKey(0)
cv2.destroyAllWindows()

enter image description here

您需要创建图像的副本以避免使用与 img 相同的内存位置。不确定这是否是您正在寻找的 only_red,但是将蓝色和绿色的所有三个通道都设置为 0 将避免将其视为单通道灰度图像。

    ##### Image processing ####
import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread('/home/pi/Documents/testcode_python/Tractor_actual/Pictures/result2.jpg') #reads as BGR
print(img.shape)

no_blue=img.copy() # copy of img to avoid using the same memory location as img
no_green=img.copy() # copy of img to avoid using the same memory location as img
only_red=img.copy() # similarly to above. 

# You also need all three channels of the RGB image to avoid it being interpreted as single channel image.
only_red[:,:,0] = np.zeros([img.shape[0], img.shape[1]])
only_red[:,:,1] = np.zeros([img.shape[0], img.shape[1]])
# Puts zeros for green and blue channels

no_blue[:,:,0]=np.zeros([img.shape[0], img.shape[1]]) #Puts Zeros on Blue channels for "no_blue"
no_green[:,:,1]=np.zeros([img.shape[0], img.shape[1]])

print(no_blue.shape)

cv2.imshow('Original',img)
cv2.imshow('No Blue',no_blue)
cv2.imshow('No Green',no_green)
cv2.imshow('Only Red', only_red)
cv2.waitKey(0)
cv2.destroyAllWindows()