Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

values at coordinates to image

I have a text file with measurement data which looks like this.

x   y   z
1   3   -2
2   1   -3
3   1   1
2   2   3
1   2   2
2   3   0

This would imply the following measurement (on an x,y grid)

-2   0
 2   3
    -3   1

I want to create an image from these values where no measurement would mean that the image is transparent. If possible I would like to map the z values (from for example -9.4 to +3.2) to a colormap such as colormap.jet

I've tried to do this using the Python Image Library and putpixel but this is very slow and I'm sure there must be a better way of doing this.

My current code: basePath = os.path.dirname(os.path.realpath(file)) # defines the directory where the current file resides srcFiles = glob.glob('*.pts')

for fileName in srcFiles:

data = pd.read_csv(os.path.join(basePath, fileName), names=['x', 'y', 'z'], delim_whitespace=True)

print fileName
maxX = data.x.max()
minX = data.x.min()
maxY = data.y.max()
minY = data.y.min()
minZ = data.z.min()
maxZ = data.z.max()

width = maxX-minX
height = maxY-minY

img = Image.new('L', (int(width), int(height)))


for x in range(int(width)):
    for y in range(int(height)):
        value = data[(data['x'] == (minX+x)) & (data['y'] == (minY+y))]['z']
        if len(value) == 0:
            value = 99.;

        img.putpixel((x,y),int(value))

img.save('test.png')
like image 700
Yorian Avatar asked Nov 26 '25 22:11

Yorian


1 Answers

Maybe you should just use a numpy matrix to manipulate the image. I didn't do the csv read part as you already have it. The masked array let you have transparent pixels.

import numpy as np
import matplotlib.pyplot as plt

INPUT = np.array(
[[1,   3,   -2]
,[2,   1,   -3]
,[3,   1,   1]
,[2,   2,   3]
,[1,   2,   2]
,[2,   3,   0]])

# get ranges
xmin = INPUT[:,0].min()
xmax = INPUT[:,0].max()
ymin = INPUT[:,1].min()
ymax = INPUT[:,1].max()
zmin = INPUT[:,2].min()
zmax = INPUT[:,2].max()

# create array for image : zmax+1 is the default value
shape = (xmax-xmin+1,ymax-ymin+1)
img = np.ma.array(np.ones(shape)*(zmax+1))

for inp in INPUT:
    img[inp[0]-xmin,inp[1]-ymin]=inp[2]

# set mask on default value
img.mask = (img==zmax+1)

# set a gray background for test
img_bg_test =  np.zeros(shape)
cmap_bg_test = plt.get_cmap('gray')
plt.imshow(img_bg_test,cmap=cmap_bg_test,interpolation='none')

# plot
cmap = plt.get_cmap('jet')
plt.imshow(img,cmap=cmap,interpolation='none',vmin=zmin,vmax=zmax)
plt.colorbar()

plt.imsave("test.png",img)
plt.show()
plt.close()

output note that the imsave does not save the figure I show here but the image as you want which wouldn t be interesting with 3x3 pixels.

like image 92
Vince Avatar answered Nov 28 '25 11:11

Vince



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!