Search code examples
opencvjpeg

Way to convert 12-bit jpg on linux


We use OpenCV on linux to read and process regular 8-bit JPGs.

We are now receiving 12-bit JPGs from a specific piece of hardware. OpenCV cannot read these, nor can anything else I've tried. Is there a utility or library for linux that would enable us to process these? Perhaps converting to an 8-bit format?

The latest libjpeg supports 12-bit JPG as a compile-time option. Meaning it would not be easy to write software that supports regular 8-bit and 12-bit jpg at the same time. But I'm wondering if someone has solved this already.


Solution

  • I have a couple of improvements to your proposed technique.

    Firstly, you can simplify your process and remove the need to install and be reliant on ImageMagick by making djpeg emit a PPM file, because OpenCV can read them anyway without any libraries. So your command would become:

    djpeg > result.ppm < some12bitBadBoy.jpg
    

    Secondly, if you do that, you actually get a 12/16-bit PPM file, so you retain more colour resolution into the process!

    identify -verbose result.ppm
    
    Image: a.ppm
      Format: PPM (Portable pixmap format (color))
      Mime type: image/x-portable-pixmap
      Class: DirectClass
      Geometry: 227x149+0+0
      Units: Undefined
      Type: TrueColor
      Endianess: Undefined
      Colorspace: sRGB
      Depth: 12-bit                   <---
      Channel depth:
        Red: 12-bit                   <---
        Green: 12-bit                 <---
        Blue: 12-bit                  <---
      Channel statistics:
        Pixels: 33823
        Red:
          min: 514  (0.125519)
          max: 4095 (1)
          mean: 2350.62 (0.574022)
          standard deviation: 1102.04 (0.269119)
          kurtosis: -1.39076
          skewness: 0.13609
          entropy: 0.971255
        Green:
          min: 305  (0.0744811)
          max: 4095 (1)
          mean: 1453.69 (0.354991)
          standard deviation: 852.147 (0.208095)
          kurtosis: 2.42348
          skewness: 1.77043
          entropy: 0.918006
        Blue:
          min: 213  (0.0520147)
          max: 4095 (1)
          mean: 1309.16 (0.319698)
          standard deviation: 890.453 (0.217449)
          kurtosis: 2.74961
          skewness: 1.92239
    ...
    ...
    

    For anyone else trying to find an elusive 12-bit JPEG, I eventually found one here.


    A further suggestion, to simplify your workflow, might be to use inotify (man page) to monitor filesystem events on your image storage area. So you could effectively be notified whenever new JPEGs arrive for analysis, then you could automagically check if 12-bit and generate a corresponding PPM file using the procedure above and move the 12-bit JPEG off to some other holding area on disk in case you need to refer back to it.

    In case you use Macs, the equivalent is fswatch which can be installed with homebrew.