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

使用最近邻规则缩放图像时遭遇numpy数组报错ValueError: setting an array element with sequence的技术求助

Fixing ValueError: setting an array element with a sequence in Your Nearest-Neighbor Image Zoom Code

Hey there! Let's break down why you're running into that error and get your image zoom working properly.

The Root Cause

When you read a color image with cv2.imread(), the resulting NumPy array has a 3-dimensional shape: (height, width, 3) (one channel for each of B, G, R). But in your code, you created the zoomed array as a 2D array:

zoomed = np.zeros((rows, cols), dtype=img.dtype)

This means each element in zoomed is a single value, but you're trying to assign a 3-element sequence (the BGR pixel from the original image) to it—hence the ValueError.

The Fix

We just need to adjust the zoomed array to match the original image's dimensionality, plus a few small optimizations:

  1. Add the channel dimension to the zoomed array initialization.
  2. Use integer division (//) for cleaner index calculation.
  3. Add a check to ensure the image was loaded successfully (avoids hidden errors if the file path is wrong).
  4. Clean up OpenCV windows at the end.

Here's the corrected code:

import cv2
import numpy as np

img = cv2.imread('abc.jpg')
# Check if image loaded successfully
if img is None:
    print("Oops! Couldn't read the image file. Double-check the path.")
    exit()

rows = img.shape[0] * 2
cols = img.shape[1] * 2
# Match the original image's 3D shape (height, width, channels)
zoomed = np.zeros((rows, cols, img.shape[2]), dtype=img.dtype)

for i in range(rows):
    for j in range(cols):
        # Integer division gives the corresponding index in the original image
        zoomed[i, j] = img[i//2, j//2]

cv2.imshow('Input Image', img)
cv2.imshow('Zoomed Image', zoomed)
cv2.waitKey(0)
cv2.destroyAllWindows()  # Clean up windows after closing

Extra Notes

  • If you were working with a grayscale image, your original 2D array would have worked—but color images always need that third channel dimension.
  • Using zoomed[i, j] instead of zoomed[i][j] is the preferred way to index NumPy arrays, as it's more efficient and readable.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 18:43:12