I ran a algorithm that gave me rgb images, representing the estimated depth of the pixels of the imgs. Since it's representing a value, i wanted to convert it to greyscale. However, the rgb palette isnt linear with the level of grey.
I tried to use the image.convert line from the PIL library with the palette argument,as follows, but it didn't work.
At first i tried
import os
from PIL import Image
directory = "folder/path"
for filename in os.listdir(directory):
if filename.endswith(".jpg") or filename.endswith(".png"):
file_path = os.path.join(directory, filename)
image = Image.open(file_path)
image_gray = image.convert('L')
image_gray.save(file_path)
but that gave me a regular rgb to grayscale conversion, so i tried to use the custom scale like this :
import os
from PIL import Image
directory = "folder/path"
custom_scale_path = "custom-scale/path"
custom_scale = Image.open(custom_scale_path).convert('L')
for filename in os.listdir(directory):
if filename.endswith(".jpg") or filename.endswith(".png"):
file_path = os.path.join(directory, filename)
image = Image.open(file_path)
image_gray = image.convert('P', palette=custom_scale)
image_gray.save(file_path)
Any suggestion ?
You can solve this by building a lookup table from the given color scale and then finding the closest point for every pixel to it. Assumption would be that the image does not contain any RGB that has no representation in the given scale.
Here is how I did it:
First, read the image and the scale and transform it to arrays.
Next, construct the lookup table (lut) from your scale.
At this point, you need to put in actual numbers for the height (or depth) map, that is connected to your scale. I simply used 0 and 1 here. What we can see is that above 0.6, you will not be able to discriminate values anymore with the given color scale, since all RGB values are constant.
Now comes the conversion function. It calculates the minimum distance of any given RGB tuple to the values in the lookup table and returns the corresponding value.
Now apply it to your data file. This takes a while in python for larger pictures, so you may have to put in some additional work to make it faster.
And plot or use elsewhere...
(I did not use the grayscale color map for the plot, since there is this one area, far away, which would visualy dominate the image.)