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

如何解决Python图像下采样时‘setting an array element with a sequence’错误?

图像下采样代码错误解决方法

错误原因

cv2.imread("Barbara.JPG", -1)会读取图像的原始通道数(彩色图为3通道BGR格式),但你创建的输出数组g = np.zeros([nr_s, nc_s], dtype='uint8')是单通道的。当你把f[x*sampling_rate, y*sampling_rate](一个包含3个值的数组)赋值给单通道的g[x,y]时,就会触发"setting an array element with a sequence"错误——无法将多通道像素值序列塞进单通道的单个元素里。

另外代码中未实现ShowImage函数,运行时也会报错,需要补充实现。


方案1:处理彩色图像(保留多通道)

修改下采样函数,让输出数组与输入图像通道数一致:

import numpy as np
import cv2

def ShowImage(img):
    cv2.imshow('Image', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

def image_downsampling(f, sampling_rate):
    nr, nc = f.shape[:2]
    # 获取图像通道数,灰度图为1,彩色图为3
    channels = f.shape[2] if len(f.shape) == 3 else 1
    nr_s, nc_s = nr // sampling_rate, nc // sampling_rate
    # 创建对应通道数的输出数组
    g = np.zeros([nr_s, nc_s, channels], dtype='uint8')
    for x in range(nr_s):
        for y in range(nc_s):
            g[x, y] = f[x*sampling_rate, y*sampling_rate]
    return g

def main():
    img1 = cv2.imread("Barbara.JPG", -1)
    img2 = image_downsampling(img1, 2)
    ShowImage(img1)
    ShowImage(img2)

main() 

方案2:转为灰度图后处理

如果只需要灰度图的下采样,读取时直接转为单通道灰度图:

import numpy as np
import cv2

def ShowImage(img):
    cv2.imshow('Image', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

def image_downsampling(f, sampling_rate):
    nr, nc = f.shape[:2]
    nr_s, nc_s = nr // sampling_rate, nc // sampling_rate
    g = np.zeros([nr_s, nc_s], dtype='uint8')
    for x in range(nr_s):
        for y in range(nc_s):
            g[x, y] = f[x*sampling_rate, y*sampling_rate]
    return g

def main():
    # 直接读取为灰度图
    img1 = cv2.imread("Barbara.JPG", cv2.IMREAD_GRAYSCALE)
    img2 = image_downsampling(img1, 2)
    ShowImage(img1)
    ShowImage(img2)

main() 

内容的提问来源于stack exchange,提问作者LON CH

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 00:05:21