CMYK数组写入文本(.txt)文件并从文件(.txt)读取并创建图像

时间:2018-10-22 10:22:33

标签: numpy python-imaging-library

我正在尝试将图像转换为cmyk数组并将这些数组写入文本文件。当我从同一文件读取并尝试显示它时,出现错误。我认为我犯了一些错误,但找不到解决方案。下面的代码:

from PIL import Image
import numpy as np

imgs = Image.open('rgb.jpg').convert('CMYK')    
imgs_image = np.array(imgs)
str2 =str(imgs_image)
f=open("rgb_real_cmyk.txt","w")
f.write(str2)
f.close()

fh = open("rgb_real_cmyk.txt","r") 
string=fh.read()
file_image = np.array(string)
file_test = Image.fromarray(file_image, mode='CMYK')
file_test.save("file_image.jpeg")

错误:

  

“在fromarray中       大小= shape [1],shape [0]

     

IndexError:元组索引超出范围”

1 个答案:

答案 0 :(得分:0)

我认为问题在于您仅存储文件中所有像素的,而没有保存图像的尺寸

因此,当您将其读回时,如果您的图像是8x10像素,每个像素有4个CMYK值,那么您只会得到8x10x4值,它看起来像是320个平面元素数组,而不是矩形图像。

我想您需要说为什么,并且如果需要更完整的答案,是否可以接受在文件开头存储图像尺寸。

最容易想到的是numpy.savetxt("CMYK.txt", YourNumpyArray),但是仅适用于一维或二维数组,而您的是3-D数组。最简单的解决方案可能是as shown here


我想您知道您可以将CMYK图像另存为易于查看的TIF ...

#!/usr/local/bin/python3
from PIL import Image
import numpy as np

img = Image.open('rgb.jpg').convert('CMYK')    
img.save('result.tif')
相关问题