鱼C论坛

 找回密码
 立即注册
查看: 2901|回复: 1

为什么会报错too many indices for array

[复制链接]
发表于 2018-5-24 10:29:10 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
from PIL import Image
import os
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt


def restore1(u, sigma, v, k):
    m = len(u)
    n = len(v)
    a = np.zeros((m, n))
    # 重构图像
    a = np.dot(u[:, :k], np.diag(sigma[:k])).dot(v[:k, :])
    # 上述语句等价于:
    # for i in range(k):
    #     ui = u[:, i].reshape(m, 1)
    #     vi = v[i].reshape(1, n)
    #     a += sigma[i] * np.dot(ui, vi)
    a[a < 0] = 0
    a[a > 255] = 255
    return np.rint(a).astype('uint8')


if __name__ == '__main__':
    A = Image.open('lena.bmp')
    print (A)
    #将压缩重构后的图片放在Pic目录下
    output_path = r'.\Pic2'  # r表示不转义,.表示当前目录
    if not os.path.exists(output_path):
        os.mkdir(output_path)
    a = np.array(A)  #转换成矩阵
    print (a.shape)
    a_col = a[:, :, None]
    print(a_col.shape)
    K = 50
    #由于是彩色图像,所以3通道。a的最内层数组为三个数,分别表示RGB,用来表示一个像素
    u_r, sigma_r, v_r = np.linalg.svd(a_col[:, :,0])
    u_g, sigma_g, v_g = np.linalg.svd(a_col[:, :,1])
    u_b, sigma_b, v_b = np.linalg.svd(a_col[:, :,2])
    plt.figure(facecolor = 'w', figsize = (10, 10))
    mpl.rcParams['font.sans-serif'] = [u'simHei']
    mpl.rcParams['axes.unicode_minus'] = False

    for k in range(1, K + 1):
        print (k)
        R = restore1(u_r, sigma_r, v_r, k)
        G = restore1(u_g, sigma_g, v_g, k)
        B = restore1(u_g, sigma_g, v_g, k)
        I = np.stack((R, G, B), axis = 2)

        # 如果读入的图片是png
        # Image.fromarray(I).save('%s\\svd_%d.png' % (output_path, k), 'png')
        # 如果读入的图片是jpg
        Image.fromarray(I).save('%s\\svd_%d.jpg' % (output_path, k), 'jpeg')
        if k <= 12:
            plt.subplot(3, 4, k)
            plt.imshow(I)
            plt.axis('off')
            plt.title(u'奇异值个数:%d' %  k)
    plt.suptitle(u'SVD与图像分解', fontsize = 20)
    plt.tight_layout(0.1, rect = (0, 0, 1, 0.92))
    plt.show()



小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2018-5-24 11:02:32 | 显示全部楼层
具体是哪一行的哪一句提示这个错误信息
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-9-10 06:57

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表