CSV到python中的图像

2024-05-17 06:57:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用csv数据创建一个图像。

我正在阅读csv:

f = open('file.csv', 'rb')
reader = csv.reader(f)

从这里开始,我想制作一个灰度图像,将列表中的每一行数字转换成图像文件中的一行强度。

不确定什么有用,但以下是有关我的csv文件的一些详细信息: 使用浮点,列:315,行:144

谢谢


Tags: 文件csv数据图像列表图像文件详细信息数字
3条回答

对于一个非常简单的解决方案,如果您只想了解图像的外观,可以使用pgm格式。

您可以通过将像素写为ascii来创建它。链接会更详细,但要点是您有一个格式的文件:

P2 //which format it is
width height //dimensions
maxValue //the highest value a pixel can have (represents white)
a b c ... //the pixel values (new line needed at the end of each row)

如何从CSV中获取值应该很简单,然后可以使用如下函数(未测试):

def toFile(array, filename):
    f = file(filename, 'w')
    f.write("P2\n%d %d\n255\n" %(len(array[1]), len(array))
    for i in array:
        for j in i:
            f.write("%d " %(j))
        f.write("\n")
    f.close()

两个步骤:

  1. 使用genfromtxt将csv文件转换为numpy array

来自@Andrew onHow to read csv into record array in numpy?

from numpy import genfromtxt
my_data = genfromtxt('my_file.csv', delimiter=',')
  1. 然后save the numpy array as an image

相关问题 更多 >