【问题标题】:cv2.Imshow() show same channel color on different imagescv2.Imshow() 在不同图像上显示相同的通道颜色
【发布时间】:2021-03-26 09:42:12
【问题描述】:

我遇到了一个很奇怪的问题。 Imshow() 为前三个 imshow 显示相同的图像 - 为什么? (只有红色通道,蓝色和绿色好像都归零了) 我正在创建原始图像的副本,但似乎这些操作会影响所有图像。 第四个 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

【问题讨论】:

  • 我认为您需要复制图像。正如上面所写,您的 no_blue、no_green 和 only_red 都指向同一个图像。见stackoverflow.com/a/16535453/5386938
  • 顺便说一句,您可以将数组的子集设置为单个标量,只需正常分配即可。 IE。你可以做no_blue[:, :, 0] = 0。您不必构造一个单独的数组然后分配值,这会更慢并且没有任何作用。
  • 谢谢!制作副本解决了这个问题。非常感谢您的快速支持。

标签: python cv2 imshow imread


【解决方案1】:

您需要创建图像的副本以避免使用与 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()

【讨论】:

  • 谢谢 - 就像一个魅力!我不认为它会使用相同的内存分配。
猜你喜欢
  • 2020-11-05
  • 1970-01-01
  • 1970-01-01
  • 2020-11-01
  • 2020-08-16
  • 2018-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多