gpt4 book ai didi

python - 向 3 channel 图像中的每个 channel 添加相同的值?

转载 作者:太空宇宙 更新时间:2023-11-03 21:39:14 24 4
gpt4 key购买 nike

我读了一张图片:

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

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

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)

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

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

例子:

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

上面是一个 3x4 图像(实际上是一个 3 channel 图像)。我想通过在 [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)

最佳答案

查看有关 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()

输入图片是这个:

Input

最终输出如下所示:

Output

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

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

希望对您有所帮助!

关于python - 向 3 channel 图像中的每个 channel 添加相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58196780/

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