我希望能将CSV数据转换为一张图片。
我正在使用以下代码读取CSV文件:
f = open('file.csv', 'rb')
reader = csv.reader(f)
从这里开始,我想生成一个灰度图像,将列表中每行数字翻译为图像文件中的强度线。
不确定什么是有用的,但以下是有关我的 CSV 文件的一些详细信息: 使用浮点数,列数:315,行数:144
谢谢
我希望能将CSV数据转换为一张图片。
我正在使用以下代码读取CSV文件:
f = open('file.csv', 'rb')
reader = csv.reader(f)
从这里开始,我想生成一个灰度图像,将列表中每行数字翻译为图像文件中的强度线。
不确定什么是有用的,但以下是有关我的 CSV 文件的一些详细信息: 使用浮点数,列数:315,行数:144
谢谢
两个步骤:
参考自@Andrew在如何在numpy中将csv读入记录数组?
from numpy import genfromtxt
my_data = genfromtxt('my_file.csv', delimiter=',')
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()
如果您只想了解图像的外观,可以使用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)
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()
我认为你可以尝试使用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)