Search code examples
pythonopencvlibpng

OpenCV imread posting libpng error: IEND: CRC error and not loading images


The following code prints this error out to the terminal but does not halt execution: libpng error: IEND: CRC error

import numpy as np
import cv2
import os

# image is stored in the same location as the python file
dir_path = os.path.dirname(os.path.realpath(__file__))
path = dir_path+'/test.png'

# img always gets set as a NoneType
img = cv2.imread(path)

Here is the test image in question (yes it is blank): enter image description here

Some Google-Fu revealed that there was a bug with the Anaconda package of libpng a while back that could cause this problem and the suggestion was to update it. I did that to no effect and so, for good measure, I also went back and make sure the most recent version of libpng was installed on my machine(s). Again, no change.

On top of that I've tried a number of different variations and operating conditions of the code with still no change. Specifically, I've tried:

  • changing the image to a .jpg. The error doesn't pop up, obviously because it is not longer using libpng, but the image still returns as a NoneType.
  • passing in extra flags like cv2.IMREAD_GRAYSCALE
  • Installing opencv (both versions 3.4.4.19 and 3.4.5.20) and numpy in a virtualenv and running it.
  • Running it on my Windows laptop (Anaconda 3.6.5) using WSL and a Raspberry Pi (3.5.3)

As an aside, I've been using OpenCV on and off for over two years with few problems and it's hurting my pride that I can't get something so simple/stupid working. I'm about to start diving into the libpng docs, but I would greatly appreciate any comments or thoughts you have.


Solution

  • If you run pngcheck on the image, it will tell you that the checksum of the IEND chunk is incorrect:

    pngcheck -v blank.png 
    

    Output

    File: blank.png (79830 bytes)
      chunk IHDR at offset 0x0000c, length 13
        2560 x 1600 image, 32-bit RGB+alpha, non-interlaced
      chunk IDAT at offset 0x00025, length 8192
        zlib: deflated, 32K window, fast compression
      chunk IDAT at offset 0x02031, length 8192
      chunk IDAT at offset 0x0403d, length 8192
      chunk IDAT at offset 0x06049, length 8192
      chunk IDAT at offset 0x08055, length 8192
      chunk IDAT at offset 0x0a061, length 8192
      chunk IDAT at offset 0x0c06d, length 8192
      chunk IDAT at offset 0x0e079, length 8192
      chunk IDAT at offset 0x10085, length 8192
      chunk IDAT at offset 0x12091, length 5937
      chunk IEND at offset 0x137ce, length 0
      CRC error in chunk IEND (computed ae426082, expected ae426080)
    

    If you dump the file in hex:

    xxd image.png > hex
    

    And then edit the last byte in any normal editor to make it correct, you can rebuild the file with:

    xxd -r < hex > recovered.png