You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

生成自动立体图时NumPy数组索引错误:序列赋值异常

Python自动立体图生成中的NumPy数组索引错误解决

问题场景

使用Python生成自动立体图(autostereogram)时触发NumPy数组索引错误。将图像转换为NumPy数组后传入生成函数,函数通过水平重复图像、偏移特定像素实现立体效果,自动立体图数组的[r,c]坐标基于纹理数组坐标计算得到,但执行代码时出现维度不匹配的报错。

相关代码如下:

import numpy as np
import matplotlib.pyplot as plt
import skimage, skimage.io
from PIL import Image

plt.rcParams['figure.dpi'] = 150


def normalize(depthmap):
    """将深度图数值归一化到[0, 1]范围"""
    if depthmap.max() > depthmap.min():
        return (depthmap - depthmap.min()) / (depthmap.max() - depthmap.min())
    else:
        return depthmap
    
def display(img, colorbar=False):
    """显示图像"""
    
    plt.figure(figsize=(10, 10))
    if len(img.shape) == 2:
        i = skimage.io.imshow(img, cmap='gray')
    else:
        i = skimage.io.imshow(img)
    i = skimage.io.imshow(img)
    if colorbar:
        plt.colorbar(i, shrink=0.5, label='depth')
    plt.tight_layout()
    print("display called")


def make_pattern(shape=(16, 16), levels=64):
    """生成灰度随机图案"""
    return np.random.randint(0, levels - 1, shape) / levels


def create_circular_depthmap(shape=(600, 800), center=None, radius=100):
    """生成圆形深度图"""
    depthmap = np.zeros(shape, dtype=float)
    r = np.arange(depthmap.shape[0])
    c = np.arange(depthmap.shape[1])
    R, C = np.meshgrid(r, c, indexing='ij')
    if center is None:
        center = np.array([r.max() / 2, c.max() / 2])
    d = np.sqrt((R - center[0])**2 + (C - center[1])**2)
    depthmap += (d < radius)
    return depthmap  


def make_autostereogram(depthmap, pattern, shift_amplitude=0.1, invert=False):
    """从深度图和图案生成自动立体图"""
    print("make_autostereogram called")
    depthmap = normalize(depthmap)
    if invert:
        depthmap = 1 - depthmap
    autostereogram = np.zeros_like(depthmap, dtype=pattern.dtype)
    for r in np.arange(autostereogram.shape[0]):
        for c in np.arange(autostereogram.shape[1]):
            if c < pattern.shape[1]:
                autostereogram[r, c] = pattern[int(r % pattern.shape[0]), c]
            else:
                shift = int(depthmap[r, c] * shift_amplitude * pattern.shape[1])
                autostereogram[r, c] = autostereogram[r, int(c - pattern.shape[1] + shift)]

    return autostereogram


# 注:原代码中blank_image()未定义,此处注释或替换为实际逻辑
# img = blank_image()

texture= Image.open('marble.png')
texture.show()

depthmap = create_circular_depthmap(radius=150)
depthmapImg = Image.fromarray(normalize(depthmap))

newPattern = np.array(texture)
print("new pattern: ", type(newPattern))

autostereogram2 = make_autostereogram(depthmap, newPattern)

报错信息

TypeError: only length-1 arrays can be converted to Python scalars

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\geniu\OneDrive\GW\Spring_2024\CSCI_6527\final_project.py", line 171, in <module>
    autostereogram2 = make_autostereogram(depthmap, newPattern)
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\geniu\OneDrive\GW\Spring_2024\CSCI_6527\final_project.py", line 85, in make_autostereogram
    autostereogram[r, c] = pattern[int(r % pattern.shape[0]), c] #pattern[r, c] #
    ~~~~~~~~~~~~~~^^^^^^
ValueError: setting an array element with a sequence.

问题根源

  1. 维度不匹配:depthmap是二维数组(形状为[H, W],灰度图结构),而从彩色图像转换来的newPattern是三维数组(形状为[H, W, 3],包含RGB三通道)。
  2. 数组赋值错误:代码中autostereogram = np.zeros_like(depthmap, dtype=pattern.dtype)创建的是二维数组,但尝试将三维数组pattern中的元素(一个长度为3的RGB序列)赋值给二维数组的单个位置,导致“用序列设置数组元素”的错误。

解决方案

提供两种可行方案,根据需求选择:

方案1:将彩色纹理转为灰度图

如果只需要生成灰度立体图,将加载的彩色图像转为灰度后再转换为NumPy数组:

# 修改纹理加载部分
texture = Image.open('marble.png').convert('L')  # 转为灰度图
texture.show()
newPattern = np.array(texture)

方案2:修改立体图生成逻辑,支持彩色输出

需要调整autostereogram的创建方式,使其匹配彩色纹理的三维结构:

def make_autostereogram(depthmap, pattern, shift_amplitude=0.1, invert=False):
    """从深度图和图案生成自动立体图(支持彩色)"""
    print("make_autostereogram called")
    depthmap = normalize(depthmap)
    if invert:
        depthmap = 1 - depthmap
    # 创建与pattern维度匹配的立体图数组:depthmap是[H,W],pattern是[H,W,C],所以立体图形状为[H,W,C]
    autostereogram_shape = (depthmap.shape[0], depthmap.shape[1], pattern.shape[2])
    autostereogram = np.zeros(autostereogram_shape, dtype=pattern.dtype)
    for r in np.arange(autostereogram.shape[0]):
        for c in np.arange(autostereogram.shape[1]):
            if c < pattern.shape[1]:
                autostereogram[r, c] = pattern[int(r % pattern.shape[0]), c]
            else:
                shift = int(depthmap[r, c] * shift_amplitude * pattern.shape[1])
                autostereogram[r, c] = autostereogram[r, int(c - pattern.shape[1] + shift)]

    return autostereogram

此外,原代码中blank_image()函数未定义,需要补充实现或注释掉该语句,避免额外报错。


内容的提问来源于stack exchange,提问作者T. J. Foster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 16:24:57