简体   繁体   English

从csv读取numpy数组时出错

[英]error reading back a numpy array from csv

I am working on a program to take an image and flatten it so it can be written into a CSV file. 我正在开发一个程序来拍摄图像并将其展平,以便可以将其写入CSV文件。 That part works. 那部分起作用。 I am having an issue when I try to read back the line from the CSV file. 我尝试从CSV文件中读取该行时遇到问题。 I try to reconstruct the image and I get an error of "ValueError: cannot reshape array of size 0 into shape (476,640,3)". 我尝试重建图像,但出现错误“ ValueError:无法将大小为0的数组重塑为形状(476,640,3)”。 I added sample output from the CSV file. 我从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)

The empty lines at the end of the file you posted are significant. 您发布的文件末尾的空行很重要。 They are considered rows by the CSV reader object, and will be iterated over in your for loop. CSV reader对象将它们视为行,并将在for循环中对其进行迭代。 Thus there are passes through the loop in which an empty row is converted to an array of size zero, as the row has no elements. 因此,由于该行没有元素,因此循环通过,其中将空行转换为大小为零的数组。 Resizing that obviously fails. 调整大小显然会失败。

Either remove the rows from the CSV file, or directly use the np.loadtxt function, specifying the delimiter=',' option. 从CSV文件中删除行,或者直接使用np.loadtxt函数,并指定delimiter=','选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM