Numpy and 16-bit PGM

后端 未结 5 778
梦毁少年i
梦毁少年i 2020-12-03 05:17

What is an efficient and clear way to read 16-bit PGM images in Python with numpy?

I cannot use PIL to load 16-bit PGM images due to a PIL bug. I can read in the hea

5条回答
  •  孤城傲影
    2020-12-03 06:05

    import re
    import numpy
    
    def read_pgm(filename, byteorder='>'):
        """Return image data from a raw PGM file as numpy array.
    
        Format specification: http://netpbm.sourceforge.net/doc/pgm.html
    
        """
        with open(filename, 'rb') as f:
            buffer = f.read()
        try:
            header, width, height, maxval = re.search(
                b"(^P5\s(?:\s*#.*[\r\n])*"
                b"(\d+)\s(?:\s*#.*[\r\n])*"
                b"(\d+)\s(?:\s*#.*[\r\n])*"
                b"(\d+)\s(?:\s*#.*[\r\n]\s)*)", buffer).groups()
        except AttributeError:
            raise ValueError("Not a raw PGM file: '%s'" % filename)
        return numpy.frombuffer(buffer,
                                dtype='u1' if int(maxval) < 256 else byteorder+'u2',
                                count=int(width)*int(height),
                                offset=len(header)
                                ).reshape((int(height), int(width)))
    
    
    if __name__ == "__main__":
        from matplotlib import pyplot
        image = read_pgm("foo.pgm", byteorder='<')
        pyplot.imshow(image, pyplot.cm.gray)
        pyplot.show()
    

提交回复
热议问题