错误从csv读回一个numpy数组

时间:2017-10-24 01:45:39

标签: python numpy

我正在开发一个程序来拍摄图像并将其展平,以便将其写入CSV文件。那部分有效。当我尝试从CSV文件中读回该行时,我遇到了问题。我尝试重建图像,我得到一个错误“ValueError:无法重塑大小为0的数组形状(476,640,3)”。我从CSV文件中添加了示例输出。

sample output

            import csv
            import cv2
            import numpy as np
            from skimage import io
            from matplotlib import pyplot as plt

            image = cv2.imread('Li.jpg')

            def process_images (img):
                img = np.array(img)
                img = img.flatten()
                return img

            def save_data(img):
                dataset = open('dataset.csv', 'w+')
                with dataset:
                    writer = csv.writer(dataset)
                    writer.writerow(img)

            def load_data():
                with open('dataset.csv', 'r') as processed_data:  
                    reader = csv.reader(processed_data)
                    for row in reader:
                        img = np.array(row , dtype='uint8')
                        img = img.reshape(476,6, 3)
                return img

            def print_image_stats (img):
                print (img)
                print (img.shape)
                print (img.dtype)

            def rebuilt_image(img):
                img = img.reshape(476,640,3)
                plt.imshow(img)
                plt.show()
                return img      

            p_images = process_images(image)

            print_image_stats(p_images)

            r_image = rebuilt_image(p_images)

            print_image_stats(r_image)

            save_data(p_images)

            loaded_data = load_data()

            #r_image = rebuilt_image(load_data)

            #print_image_stats(r_image)

1 个答案:

答案 0 :(得分:0)

您发布的文件末尾的空行很重要。它们被CSV reader对象视为行,并将在for循环中迭代。因此,通过循环,其中空行被转换为大小为零的数组,因为该行没有元素。调整大小明显失败。

从CSV文件中删除行,或直接使用np.loadtxt函数,指定delimiter=','选项。

相关问题