【问题标题】:Adding a same value to each channel in a 3 channel image?为 3 通道图像中的每个通道添加相同的值?
【发布时间】:2019-10-02 07:13:26
【问题描述】:

我读了一张图片:

img = cv2.imread("sky.png", 1)

现在,我想在每个通道的每一列中添加一个像素。我尝试的方法如下:

img[row_1, :, 0] = np.insert(img[row_1,:,0], column_1, some_value)
img[row_1, :, 1] = np.insert(img[row_1,:,1], column_1, some_value)
img[row_1, :, 2] = np.insert(img[row_1,:,2], column_1, some_value)

有没有比分别写入每个通道更好的方法?

更新: 正如我所提到的,我想添加一个新的 ,即 4x4 图像,转换为 4x5 图像。每个像素的值不同,列的顺序也不固定。例如,第一个像素插入到 3 列,第二个像素插入到 1 列,依此类推(使用预定的列集)

例子:

[
  [1,2,3,4],
  [4,5,6,7],
  [8,9,10,11]
]

以上是 3x4 图像(实际上是 3 通道图像)。我想通过在 [0,2]、[1,1]、[2,4] 处添加像素来将其转换为 3x5 图像

然后输出变成:

[
   [1,2, new-pixel-a, 3, 4],
   [4,new-pixel-b, 5, 6, 7]
   [8, 9, 10, 11, new-pixel-c]
]

所以我得到一个新图像,(3, 5)

【问题讨论】:

  • 检查this,也许有帮助。告诉我。
  • @DaemonPainter 无法理解。你知道 OpenCV 和 numpy 的例子吗?
  • 你的意思是图片高度应该增加1吗?
  • @MarkSetchell 是的。但我想为每一行插入不同的像素。对于 4x4 图像,即 5x4,我想插入 5 个不同的像素。
  • 你的问题似乎让汉斯和我都感到困惑。也许你可以先展示一个小的、简单的图像,然后它应该看起来如何?以及之前和之后的尺寸。谢谢。

标签: python numpy opencv computer-vision


【解决方案1】:

查看有关 NumPy 的 insert 方法的文档,我会想出以下解决方案:

import cv2
import numpy as np

# Read image; output image dimensions
image = cv2.imread('N8e9S.png')
print(image.shape)

# Set up column indices where to add pixels
colIdx = np.array(image.shape[0] * np.random.rand(image.shape[0]), dtype=np.int32)

# Set up pixel values to add
pixels = np.uint8(255 * np.random.rand(image.shape[0], 3))

# Initialize separate image
newImage = np.zeros((image.shape[0], image.shape[1]+1, 3), np.uint8)

# Insert pixels at predefined locations
for i in range(colIdx.shape[0]):
    newImage[i, :, :] = np.insert(image[i, :, :], colIdx[i], pixels[i, :], axis=0)

# Output (new) image dimensions
print(newImage.shape)

# Show final image
cv2.imshow('image', image)
cv2.imshow('newImage', newImage)
cv2.waitKey(0)
cv2.destroyAllWindows()

输入图片是这个:

最终输出如下:

打印输出以验证新的图像尺寸:

(241, 300, 3)
(241, 301, 3)

希望有帮助!

【讨论】:

  • 我需要在每一行中插入不同的像素。这将为每一行插入相同的像素值
  • @Amanda 这就是我理解你的问题的方式。我已经编辑了答案以插入一整行,这里有一些随机生成的像素。
  • 我已经更新了我的问题。我正在尝试插入一个新列,其中列的顺序不固定。虽然每列插入一个新像素,但顺序可能会有所不同(由预先计算的集合确定)。例如,一个像素可以到 (1,19),第二个可以到 (2, 1) 等等。本质上,将添加一个新列。
  • 还加了一个小例子
  • @Amanda 我的答案的另一个更新。我希望,我现在明白了你的想法。尽管如此,现在如果不使用列大小 + 1 的附加 newImage 并遍历所有像素,我将看不到任何解决方案,因为您有不同的列索引。至少 np.insert 调用可以简化。
猜你喜欢
  • 2020-05-07
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
  • 2017-01-29
  • 1970-01-01
  • 2018-08-20
  • 2020-08-08
  • 1970-01-01
相关资源
最近更新 更多