10

I want to read pgm image in python. I use cv2.imread('a.pgm') but it returns wrong results. In Matlab, I use imread and get the right result which is a single channel 16-bit image. But cv2.imread in python returns a 3-channel image and the pixel values are also wrong. Why it happens? How should I read the 16-bit pgm images in python? And what libraries?

Thanks in advance.

Liang Xiao
  • 1,490
  • 2
  • 14
  • 21
  • [OpenCV supports PGM images](http://docs.opencv.org/3.1.0/d4/da8/group__imgcodecs.html#gsc.tab=0). Please share your code/output/results/errors. – Billal Begueradj Apr 05 '16 at 08:54
  • [This answer](http://stackoverflow.com/a/7369986/4014959), which just uses Numpy, may be helpful. Note that some programs use native endian instead of big endian, but it looks like that answer's code handles that. – PM 2Ring Apr 05 '16 at 08:56
  • 1
    Try using the python equivalent of this: `imread("path_to_image", IMREAD_UNCHANGED)`. Your image should be the same as matlab, eventually different by a scale factor. – Miki Apr 05 '16 at 09:32

2 Answers2

10

I got it.

cv2.imread('a.pgm',-1) 

works.

Amin Khodamoradi
  • 392
  • 1
  • 6
  • 18
Liang Xiao
  • 1,490
  • 2
  • 14
  • 21
1

You can also use skimage.io library

from skimage.io import imread
image = imread("a.pgm")
burhan rashid
  • 444
  • 5
  • 11