数字图像处理图像平移报错求助:TypeError与ValueError
解决图像平移代码的TypeError和ValueError
错误根源
你遇到的两个错误本质是同一个问题:
- 调用
translation(img,50,100)时传入的是原始彩色图像img,它的形状是(高度, 宽度, 3)(RGB三通道),但你的translation函数里创建的img_q是二维数组(仅包含高和宽,无通道维度)。 - 当尝试把
img[r,c](一个包含3个RGB值的序列)赋值给img_q的单个元素时,就会触发ValueError: setting an array element with a sequence,进而引发TypeError: only size-1 arrays can be converted to Python scalars。
修复方案
下面的代码同时兼容灰度图和彩色图的平移需求,修复了维度不匹配的问题:
from skimage import io import matplotlib.pyplot as plt from skimage.color import rgb2gray import numpy as np url = ("https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/300px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg") img = io.imread(url) img_libgray = rgb2gray(img) fig, (ax1,ax2) = plt.subplots(1,2) ax1.imshow(img) ax2.imshow(img_libgray, cmap=plt.cm.gray) def translation(img,xtrans,ytrans): # 根据输入图像维度创建对应形状的空数组 if len(img.shape) == 2: # 灰度图(二维) img_q = np.zeros((img.shape[0]+ytrans, img.shape[1]+xtrans), dtype=img.dtype) elif len(img.shape) == 3: # 彩色图(三维) img_q = np.zeros((img.shape[0]+ytrans, img.shape[1]+xtrans, img.shape[2]), dtype=img.dtype) # 遍历像素完成平移 for r in range(img.shape[0]): for c in range(img.shape[1]): img_q[r+ytrans, c+xtrans] = img[r,c] return img_q # 示例1:平移灰度图 img_tr = translation(img_libgray,50,100) fig, (ax1,ax2) = plt.subplots(1,2) ax1.imshow(img_libgray, cmap=plt.cm.gray) ax2.imshow(img_tr, cmap=plt.cm.gray) # 示例2:平移彩色图(可选) # img_tr_color = translation(img,50,100) # fig, (ax1,ax2) = plt.subplots(1,2) # ax1.imshow(img) # ax2.imshow(img_tr_color) plt.show()
关键修改点
- 适配图像维度:函数自动判断输入是灰度图(二维)还是彩色图(三维),创建对应形状的输出数组,避免维度不匹配。
- 保留数据类型:添加
dtype=img.dtype,确保输出数组和原图像的数据类型一致,避免数值转换问题。 - 传入正确图像:如果要处理灰度图,调用时传入
img_libgray而非原始彩色图img。
内容的提问来源于stack exchange,提问作者Faiz Fadilah
相关产品推荐
相关产品推荐

