Gary
Gary

Reputation: 2167

Converting RGB data into an array from a text file to create an Image

I am trying to convert txt RGB data from file.txt into an array. And then, using that array, convert the RGB array into an image. (RGB data is found at this github repository: IR Sensor File.txt).

I am trying to convert the .txt file into an array which I could use the PIL/Image library and convert the array into an Image, and then put it through the following script to create my image.

My roadblock right now is converting the arrays in file.txt into an appropriate format to work with the Image function.

from PIL import Image
import numpy as np

data = [ARRAY FROM THE file.txt]
img = Image.fromarray(data, 'RGB')
img.save('my.png')
img.show()

The RGB data looks like as follows, and can also be found at the .txt file from that github repository linked above:

[[(0,255,20),(0,255,50),(0,255,10),(0,255,5),(0,255,10),(0,255,25),(0,255,40),(0,255,71),(0,255,137),(0,255,178),(0,255,147),(0,255,158),(0,255,142),(0,255,163),(0,255,112),(0,255,132),(0,255,137),(0,255,153),(0,255,101),(0,255,122),(0,255,122),(0,255,147),(0,255,66),(0,255,66),(0,255,30),(0,255,61),(0,255,0),(0,255,0),(0,255,40),(0,255,66),(15,255,0),(0,255,15)],
[(0,255,40),(0,255,45),(15,255,0),(20,255,0),(10,255,0),(35,255,0),(0,255,5),(0,255,56),(0,255,173),(0,255,168),(0,255,153),(0,255,137),(0,255,158),(0,255,147),(0,255,127),(0,255,117),(0,255,142),(0,255,142),(0,255,122),(0,255,122),(0,255,137),(0,255,137),(0,255,101),(0,255,66),(0,255,71),(0,255,61),(0,255,25),(0,255,25),(0,255,61),(0,255,35),(0,255,0),(35,255,0)],
[(0,255,15),(0,255,25),(51,255,0),(71,255,0),(132,255,0),(101,255,0),(35,255,0),(0,255,20),(0,255,91),(0,255,153),(0,255,132),(0,255,147),(0,255,132),(0,255,158),(0,255,122),(0,255,132),(0,255,142),(0,255,158),(0,255,122),(0,255,137),(0,255,142),(0,255,147),(0,255,101),(0,255,101),(0,255,86),(0,255,86),(0,255,50),(0,255,45),(0,255,50),(0,255,56),(0,255,30),(56,255,0)],
[(0,255,45),(0,255,10),(76,255,0),(127,255,0),(132,255,0)]]

Upvotes: 1

Views: 1580

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207465

I think this should work - no idea if it's decent Python:

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

# Read in entire file
with open('sensordata.txt') as f:
   s = f.read()

# Find anything that looks like numbers
l=re.findall(r'\d+',s)

# Convert to numpy array and reshape
data = np.array(l).reshape((24,32,3))

# Convert to image and save
img = Image.fromarray(data, 'RGB')
img.save('result.png')

enter image description here

I enlarged and contrast-stretched the image subsequently so you can see it!

Upvotes: 2

Related Questions