首页 > 解决方案 > 如何使用python用大小为(8,8)的二维数组替换数组最后一列的前8个元素(大小=(8,8,3))

问题描述

我有两个大小为(8,8,3)和(8,8)的数组。第一个 3D 数组的最后一列的前 8 个元素必须使用 python 替换为最后一个 2D 数组的元素。

基本上 m 处理不同尺寸的图像。m 提取图像的蓝色部分,对其进行一些计算并将其替换回来。提取的蓝色部分正在形成一个 mxn 数组,而原始图像有 dim= mxnxk。

m 目前正在处理大小为 (4,4,3) 的图像,该图像将扩展为更高维度的图像。这里 img 是图像 havg 维度 = (4,4,3),q 是从一些计算得出的数组,其结果为 (4,4)。

img = cv2.imread("ori.jpg")
print(img)

img[:,2] = q       #here q is an 4x4 array

回溯(最近一次调用最后一次):文件“C:\Python36\fresh_seminar\wm_E && extract.py”,第 195 行,在 img[:,2] = q ValueError: could not broadcast input array from shape (4,4)成型 (4,3)

这是我在最后一行代码中得到的错误

标签: python

解决方案


经过这么长时间的挣扎,我终于找到了答案。可以使用以下代码将数组 b 替换为示例图像数组的一部分。我知道它很简单,但我花了很多时间才得到它!

b = np.ones((8,8), dtype = int)     #array b of size(8,8) to be replaced
half_cover = cv2.imread("sample.jpg")  
print(half_cover)
print(half_cover.shape)              shape = (894, 894, 3)  

for i in range(8):
    for j in range(8):
        half_cover[i,j] = b[i,j]
print(half_cover)

推荐阅读