-1

I'm trying to convert an image to cmyk array and write those array to a text file. When I read from the same file and try to display it, error appears. I think I did some error but I can't found the solution. Code below:

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")

Error:

"in fromarray size = shape[1], shape[0]

IndexError: tuple index out of range"

Bonlenfum
  • 19,101
  • 2
  • 53
  • 56
Aju S
  • 41
  • 1
  • 7

1 Answers1

0

I think that the problem is that your only store the values of all the pixels in your file but you do not save the dimensions of the image.

So, when you read it back, if your image was 8x10 pixels with 4 CMYK values each, you just get 8x10x4 values, which appears to be a flat 320 element array - not a rectangular image.

I guess you would need to say why you want to do this and whether you can accept storing the image dimensions at the start of the file if you wanted a more complete answer.

The nearest thing that springs immediately to mind is numpy.savetxt("CMYK.txt", YourNumpyArray) however that is only for 1-D or 2-D arrays and yours is 3-D. The easiest solution is probably as shown here.


I presume you are aware that you can save a CMYK image as a TIF that is readily viewable...

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

img = Image.open('rgb.jpg').convert('CMYK')    
img.save('result.tif')
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • i don't think so may be but my real aim is to construct a 3d cmyk array and display it .please answer the below link "https://stackoverflow.com/questions/52873574/convert-image-to-rgb-array-using-pil-and-manually-convert-it-to-cmyk-array?noredirect=1#comment92661690_52873574" – Aju S Oct 22 '18 at 12:12
  • Please just have one clear question, rather than 2 questions and comments and links between them. Maybe you can click `edit` under the question above and say exactly what you are trying to achieve, in the question, where people will see it. Bear in mind that you can easily save a CMYK image as a TIFF file, so maybe say why that is not suitable for your purposes. Also please say whether it is necessary for the file to be human readable text and why. – Mark Setchell Oct 22 '18 at 12:20
  • I got an error when displaying my own cmyk array created.so decided to store in file and compare the real cmyk conversion and my manual conversion .Both where same but if i tried to display manual array which is not possible .So i looking for another way that the manual array stored in a file and read it ,display it as an image.I failed in both way that's why i ask the two questions. – Aju S Oct 22 '18 at 12:58