Python中将CSV转换为图像

4

我希望能将CSV数据转换为一张图片。

我正在使用以下代码读取CSV文件:

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

从这里开始,我想生成一个灰度图像,将列表中每行数字翻译为图像文件中的强度线。

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

谢谢


你所说的“Image”,是指图形绘制吗?还是尝试渲染CSV表格本身? - srj
@srj 我认为他的意思是灰色像素。 - user189
你可能需要将浮点数转换为0-255范围内的值,以生成灰度图像。 - Paul
4个回答

6

1
from numpy import genfromtxt
from matplotlib import pyplot
from matplotlib.image import imread
my_data = genfromtxt('path to csv', delimiter=',')
matplotlib.image.imsave('path to save image as Ex: output.png', my_data, cmap='gray')
image_1 = imread('path to read image as Ex: output.png')
# plot raw pixel data
pyplot.imshow(image_1)
# show the figure
pyplot.show()

0

如果您只想了解图像的外观,可以使用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()

0


我认为你可以尝试使用glob.glob,这应该会有所帮助


import numpy as np
import glob
import cv2
import csv

库升级⬆️;你知道要做什么⬇️

image_list = []

for filename in glob.glob(r'C:\your path to\file*.png'):    # '*' will count files each by one
    
    #Read
    img = cv2.imread(filename)
    flattened = img.flatten() 
    print(flattened) # recommend to avoid duplicates, see files and so on.

    #Save
    with open('output2.csv', 'ab') as f: #ab is set 
            np.savetxt(f, flattened, delimiter=",")

干杯

另外,找到一种更简单的方法,可以快速且不增加重量地处理图像/ CSV。

image_list = []
with open('train_train_.csv', 'w') as csv_file:
    csv_writer = csv.writer(csv_file, delimiter ='-')

    for filename in glob.glob(r'C:\your path to\file*.png'):

        img = cv2.imread(filename)
        image_list.append(img)
        csv_writer.writerow(img)
        print(img)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接