Quickest way to extract the bits of the colors in a .pgm image?
-
02-10-2019 - |
Question
I've got a hundred 128 x 128 .pgm files with some shapes on them and I think their color scale is 255 (not sure on this one though, so it'd be nice if a solution could also take that in consideration) and I need to extract these colors to process the images. So what I'd like to end up with would be a 128 x 128 matrix with each element having a value between 0 - 255, assuming the 256 colors example.
As for the language, anything in Python/Java/C# will do, preferably in that order. I can use either Windows or Linux so exclusive libraries are not an issue.
Solution
As far as a python solution goes, I believe PIL supports .pgm files. In that case (using numpy as the array container, but this part is optional):
(Edit: Re-read your question and realized that you specifically wanted grayscale, rather than RGB... Which I should have realized from the .pgm format, anyway...)
import Image
import numpy as np
im = Image.open('test.pgm')
# Convert to grayscale (single 8-bit band), if it's not already...
im = im.convert('L')
# "data" is a uint8 (0-255) numpy array...
data = np.asarray(im)
OTHER TIPS
P ortable G ray M ap format is so trivial that I would consider a matter of honor to write a parser for pgm files yourself in whatever language you need. Each value read from PGM file would correspond to RGB
255*Value/Max_Valuebyte.
good luck.