Ask Your Question

Revision history [back]

Can not imread ASCII-based PBM, PGM, PPM

How can I read from Python cv2 module nad imread function any of the ASCII-based netpbm formats?

All of these fail for me i.e . returned for img is None:

img = cv2.imread('F:\\a.pbm')
img = cv2.imread('F:\\a.pgm')
img = cv2.imread('F:\\a.ppm')

I have tried various flags like cv2.IMREAD_UNCHANGED, cv2.IMREAD_COLOR, etc. but without any usable effect.

How can I access PPM via Python API?

Can not imread ASCII-based PBM, PGM, PPM

How can I read from Python cv2 module nad imread function any of the ASCII-based netpbm formats?

All of these fail for me i.e . returned for img is None:

img = cv2.imread('F:\\a.pbm')
img = cv2.imread('F:\\a.pgm')
img = cv2.imread('F:\\a.ppm')

I have tried various flags like cv2.IMREAD_UNCHANGED, cv2.IMREAD_COLOR, etc. but without any usable effect.

How can I access PPM via Python API?


UPDATE:

The problem was due to broken PPM file which did not conform to the there is a newline character at the end of each line

P3
# broken.ascii.ppm
2 2
255
 15 158 150   200 175 150
230 170 150    25 248 150 # newline was missing here

I've learned taht imread does fail for such broken image with

error: (-2) Unexpected end of input stream in function cv::RBaseStream::readBlock

but it does not raise any Python exception.

This error was completely unnoticeable while running in Jupyter or under debugger in VSCode. My bad though that I have not checked the verbose debugger output more carefully.

It eventually revealed itself when running a regular script (copied below) from command line:

imread_('D:\workshop\opencv\pnm\a.ascii.ppm'): can't read data: OpenCV(3.4.1) 
  C:\Miniconda3\conda-bld\opencv-suite_1533128839831\work\modules\imgcodecs\src\bitstrm.cpp:110:
    error: (-2) Unexpected end of input stream in function cv::RBaseStream::readBlock

The script:

import cv2
import os.path
data_dir = os.path.dirname(os.path.abspath(__file__))

# Samples from:
# https://people.sc.fsu.edu/~jburkardt/data/pbma/pbma.html
# https://people.sc.fsu.edu/~jburkardt/data/pgma/pgma.html
# https://people.sc.fsu.edu/~jburkardt/data/ppma/ppma.html
# plus the broken one
image_files = [
    'circle.ascii.pbm',
    'circle.png',
    'lena.ascii.pgm',
    'lena.png',
    'snail.ascii.ppm',
    'snail.png',
    'broken.ascii.ppm'
]

for file_name in image_files:
    file_path = os.path.join(data_dir, file_name)
    assert os.path.isfile(file_path), 'file \'{0}\' does not exist'.format(file_path)
    img = cv2.imread(file_path)
    if img is not None:
        print('img.size: ', img.size)
    else:
        print('imread({0}) -> None'.format(file_path))