从 csv 读回 numpy 数组时出错

error reading back a numpy array from csv

我正在开发一个程序来拍摄图像并将其展平,以便将其写入 CSV 文件。那部分有效。当我尝试从 CSV 文件中读回该行时遇到问题。我尝试重建图像,但出现 "ValueError: cannot reshape array of size 0 into shape (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)

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

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