Skip to content

Introduce a way to radically reduce the output file size (sacrificing image quality) #541

Closed

Description

@heinrich-ulbricht

Is your feature request related to a problem? Please describe.
My use case is "scanning" documents with a smartphone camera, then archiving those "scans" as low-quality monochrome images. But OCR should be done beforehand on the high-quality images.

I describes this in more detail here: #443 (comment)

Furthermore I see a discussion covering a similar topic here: #293

Describe the solution you'd like
I want greater control of image quality for the images embedded into the PDF (after doing OCR). I can imagine those possible solutions (each point is a complete solution):

  • add a parameter that forces all images to be converted to 1 bpp images (low effort)
  • add a parameter allowing arbitrary shell commands to be passed that will be executed by OCRmyPDF on the images in the temporary folder, before OCRmyPDF handles them further (high effort, security implications?)
  • introduce multiple parameters that allow for more control of the things that go on in the optimization step (probably here) (medium effort?)

Additional context
I'm currently evaluating how to achieve my goal with the least effort. I see two approaches:

  1. let OCRmyPDF do it's thing on high quality images/PDFs; post-process manually using pikepdf using a Python script that replaces the high quality images with low quality ones in the PDF (I have a working PoC, but it's not pretty)
  2. modify OCRmyPDF

I'm not sure about the second approach - where would be a good point to start? One approach could be:

  1. using PNG images in the input PDF file, then
  2. forcing pngquant to convert them to 1 bpp (here?)
  3. this could trigger PNG rewriting as G4 (here)

@jbarlow83 Does this sound right?

Activity

  1. jbarlow83 commented on Apr 24, 2020

    @jbarlow83
    Collaborator

    I would go with modifying ocrmypdf, and:

    1. Always input JPG
    2. Replace pngquant.quantize with code that always converts the image to 1bpp (e.g. just use PIllow).
    3. You will actually want to install jbig2enc. JBIG2 outperforms G4 in size and is still widely supported. 1bpp PNGs will always be converted to JBIG2 when a jbig2 encoder is available. You might even want JBIG2 in lossy mode, provided the dangers of lossy mode are acceptable to you (see documentation and the "6-8" problem).

    Instead of forcing PNG input, you could also uncomment the optimize.py:523 "try pngifying the jpegs" which as the name suggests, speculatively converts JPEGs to PNGs. I believe this had a few corner cases to be worked out and is too costly in performance in the typical case, but you could try that, especially if you are forcing everything to JBIG2 anyway.

  2. heinrich-ulbricht commented on Apr 24, 2020

    @heinrich-ulbricht
    Author

    I'm giving it a try and am having some success.

    @jbarlow83 A question: This return doesn't look right since it leaves the function after handling only one image. Is this ok?

    https://github.com/jbarlow83/OCRmyPDF/blob/58abb5785cf55d0cfddeee017e81ca4a8250a94c/src/ocrmypdf/optimize.py#L426

    For me this leads to only one of multiple images being handled in a multi-page PDF, where each page contains one image. (Since the loop cannot finish.)

    And one (related?) curiosity: I managed to modify the conversion pipeline such that I now have multiple 1 bpp PNGs waiting in the temp folder to be handled. If there is only one such PNG the resulting PDF looks fine. If there are multiple such images the resulting PDF is distorted. Looking at the images in the temp folder I got:

    • my quality-reduced PNGs
    • the corresponding generated TIFs - each looking good

    Then the code converts those TIFs to JBIG2 file(s) by invoking the jbig2 tool. This seems to be errorneous if there are multiple TIFs (leading to distortions in the final PDF). It works for one TIF though. So the question is: do you have a test in place checking that PDFs with multiple 1 bpp images can correctly be converted to the JBIG2 format? Or could this be a bug?

    Note: I suspect that above mentioned return prevented multiple JBIG2 files from ever being inserted into the final PDF - since the loop always terminates after generating one TIF.

    (But this might also be me not understanding how the final JBIG2 handling works. I might have broken something with my modifications.)

    Edit: the debug output shows me this command line that is being used by OCRmyPDF:

      DEBUG - Running: ['jbig2', '-b', 'group00000000', '-s', '-p', '/tmp/com.github.ocrmypdf.ylclub9u/images/00000032.tif', '/tmp/com.github.ocrmypdf.ylclub9u/images/00000028.tif', '/tmp/com.github.ocrmypdf.ylclub9u/images/00000030.tif']
    

    The TIF files look good.

  3. heinrich-ulbricht commented on Apr 24, 2020

    @heinrich-ulbricht
    Author

    I found the reason why my PDF containing the 1 bpp JBIG2 images was distorted. The color space of the embedded images was not correct. It was still /DeviceRGB:
    image
    But correct would be /DeviceGray.

    I was able to quick-fix this by inserting im_obj.ColorSpace = Name("/DeviceGray") right before this line:
    https://github.com/jbarlow83/OCRmyPDF/blob/58abb5785cf55d0cfddeee017e81ca4a8250a94c/src/ocrmypdf/optimize.py#L340
    The PDF now looks good.

    Hypothesis: it was never intended to change the color space during image optimization?

    Edit:
    Suggested fix:

    if (Name.BitsPerComponent in im_obj and im_obj.BitsPerComponent == 1):
      log.debug("Setting ColorSpace to /DeviceGray")
      im_obj.ColorSpace = Name("/DeviceGray")
    

    Edit2:
    Better fix?
    Add im_obj.ColorSpace = Name("/DeviceGray") here:
    https://github.com/jbarlow83/OCRmyPDF/blob/58abb5785cf55d0cfddeee017e81ca4a8250a94c/src/ocrmypdf/optimize.py#L430

  4. heinrich-ulbricht commented on Apr 24, 2020

    @heinrich-ulbricht
    Author

    I implemented and pushed a solution that works for me and is basically a shortcut to TIF generation (see above linked commit). I added a new user script option that can be used to run arbitrary shell commands on images. This user script takes the source and destination file pathes as input parameter and must convert the source image to a 1 bpp TIF.

    The shell script that works for me looks like this:

    #!/bin/sh
    convert -colorspace gray -fill white -sharpen 0x2 "$1" - | jpegtopnm | pamthreshold | pamtotiff -g4 > "$2"
    

    This requires ImageMagick and netpbm-progs to be installed. But one could use other conversion tools here as well. pamthreshold implements a nice dynamic threshold.

    The command that I used to test looks like this:

    ocrmypdf --user-script-jpg-to-1bpp-tif shell.sh --jbig2-lossy -v 1 -O3 in.pdf out.pdf

    • in.pdf: 791 KB (created from three colored JPGs using img2pdf)
    • out.pdf: 72 KB
    • Optimize ratio: 11.19 savings: 91.1%

    I'm not opening a pull request since the solution is very narrow to my use case. And right now it only handles JPEG images. But maybe somebody finds this useful as a starting point.

  5. jbarlow83 commented on Apr 25, 2020

    @jbarlow83
    Collaborator

    I suspect that above mentioned return prevented multiple JBIG2 files from ever being inserted into the final PDF - since the loop always terminates after generating one TIF.

    You are correct, those returns are wrong and will suppress multiple images per file. That's a great catch.

    Hypothesis: it was never intended to change the color space during image optimization?

    Also correct. /DeviceGray is not correct in general, but probably suitable for your use case. Some files will specify a complex colorspace instead of /DeviceRGB and changing to /DeviceGray may not be correct, so optimize tries to avoid changing colorspace. It is also possible to specify a 1-bit color colorspace, e.g. 0 is blue and 1 is red.

    I'm not opening a pull request since the solution

    Agreed - that's a lot of new dependencies to add.

  6. andersjohansson commented on Jun 25, 2020

    @andersjohansson

    I also needed exactly this!

    I tried to rebase unto master, missed some things in the manual merges required and added them afterwards, so my branch doesn’t look so clean right now. But here it is: https://github.com/andersjohansson/OCRmyPDF/tree/feature/github-541-reduce-output-file-size-v10

    It works fine now though! Thanks!

  7. jbarlow83 commented on Jun 25, 2020

    @jbarlow83
    Collaborator

    userscript.py could be structured as a plugin instead (new feature for 10.x). You'd need to create a new hook as well by adding it to pluginspec.py, and then we could have a generic, pluggable interface for people who want to optimize images more aggressively.

  8. andersjohansson commented on Jun 26, 2020

    @andersjohansson

    If @heinrich-ulbricht or anyone else is interested in looking more into this in the future, see also the comments that @jbarlow83 added here: andersjohansson@4e5b68f

  9. rmast commented on Nov 7, 2021

    @rmast

    What about using MRC compression to visually keep the file as much as the original but loosing lots of size as @jbarlow83 mentioned here:

    #836 (comment)

    (We do not do page color segmentation at this time, i.e., finding regions of a page or image that can be represented with a reduced colorspace. It's not an easy feature to implement and will probably need a corporate sponsor so that I can work on it full time for a few weeks. You do get better compression if you're able to work with the original PDFs.)

    You could just look at how closed source DjVuSolo 3.1 does reach astonishing sizes with really legible results, and even keeping color in JBIG2-like JB2. With DjVuToy you can transform those DjVu's into PDF's that are only about twice as big.

    With https://github.com/jwilk/didjvu there has been an attempt to open source this MRC-mechanism, however with some inconveniences that keep files too big to be a serious candidate to replace the old DjVuSolo 3.1 in the Russian user group.

    However many DjVu-patents have expired, so there might be some valuable MRC-knowledge in those patents, as @jsbien suggested.

    jwilk/didjvu#18

  10. jbarlow83 commented on Nov 8, 2021

    @jbarlow83
    Collaborator

    @rmast This is interesting information and could be helpful if I ever get the opportunity to implement this. Thanks.

  11. MerlijnWajer commented on Nov 24, 2021

    @MerlijnWajer

    (Found this through @rmast) -- If you're looking for a MRC implementation, https://github.com/internetarchive/archive-pdf-tools does this when it creates PDFs with text layers (it's mostly like OCRMyPDF but doesn't attempt to do OCR and requires that be done externally) - the MRC code can also be used as a library, although I probably need to make the API a bit more ... accessible. @jbarlow83 - If you're interested in this I could try to make a more accessible API. Alternatively, I could look at improving the "pdf recoding" method some where the software compresses an existing PDF by replacing the images with MRC compression images, so then one could just run recode_pdf after OCRmyPDF has done its thing.

  12. jbarlow83 commented on Nov 24, 2021

    @jbarlow83
    Collaborator

    @MerlijnWajer Thanks for the suggestion - that is impressive work. Unfortunately it's license-incompatible (AGPL) and also uses PyMuPDF as its PDF generator. I like PyMuPDF and used it previously, but it relies on libmupdf which is only released as a static library and doesn't promise a stable interface, meaning that Linux distributions won't include it.

    But setting it up through a plugin interface, calling recode_pdf by command line, would certainly be doable.

  13. 76 remaining items

  14. mara004 commented on Dec 1, 2023

    @mara004
    Contributor

    Thanks for the superb explanation!

    IIUC it comes down to API mode being inherently safe against ABI violations, whereas for ABI mode it all depends on the correctness of the provided bindings interface, which needs to be an exact match of the target binary's ABI.
    So the responsibility falls to bindings packagers and C library developers.

    However, I believe it should be possible to achieve a reasonable degree of ABI safety by generating bindings from the binary's compile headers and tying them together (e.g. by bundling in wheels), and upstreams being careful not to change existing functions, but instead add new ones and eventually deprecate/remove the others, ideally accompanied by semantic versioning.

  15. drtrigon commented on Oct 25, 2024

    @drtrigon

    Closing this issue since the third party plugin https://github.com/rmast/OCRmyPDF_DjVu_Optimize_Plugin larger achieves the desired objective.

    Is this plugin supposed to work the the recent OCRmyPDF version? I tried to use it with the docker version jbarlow83/ocrmypdf-alpine (16.5.1.dev2+g6ca4940a.d20240915) and it raises an error.

    Also I wonder whether the features (--grayscale-ocr and --mono-page) from the example plugin misc/example_plugin.py are "production-ready" ?

  16. rmast commented on Oct 26, 2024

    @rmast
  17. jsbien commented on Oct 26, 2024

    @jsbien

    @rmast I'm very much interested in your search for a better OCR and your improvements of Tesseract . What about kraken?
    For the time being I'm satisfied with the OCR embedded in the tools I use (Teserract I think) but some time in the future I would like to OCR some 16th century prints (training will be necessary) without using closed cloud services like Transkribus.
    As this is off the topic of this thread, you may answer in the discussion tab at https://github.com/jsbien/early_fonts_inventory or in any other place you find convenient.

  18. rmast commented on Oct 26, 2024

    @rmast
  19. jsbien commented on Oct 26, 2024

    @jsbien

    Thanks for the link. I was told kraken/escriptorium can be considered an alternative to Transcribus and this made me curious. Escriptorium is available as docker, so perhaps I will make a try in the not far future. I tried earlier several interesting systems, but they appeared no longer maintained and/or not fully documented... Nevertheless I am still interested in your experiences with the OCR engines, please share them somehow from time to time.

  20. LexLuthorX commented on Nov 28, 2024

    @LexLuthorX

    Hello, I was reading about the plugin OCRmyPDF_DjVu_Optimize_Plugin, that seems to implement MCR compression using DjVu, but I don't see any example or information in it's Github page on how to install, compile or use that plugin with OCRmyPDF.

    Has anyone used it and has information about it?
    Best regards.

  21. drtrigon commented on Nov 29, 2024

    @drtrigon

    @LexLuthorX: See my comment from Oct 25:

    Is this plugin supposed to work the the recent OCRmyPDF version? I tried to use it with the docker version jbarlow83/ocrmypdf-alpine (16.5.1.dev2+g6ca4940a.d20240915) and it raises an error.

    It was more a proof-of-concept than a real thing.

  22. beren12 commented on Jul 24, 2026

    @beren12

    I would love to easily use the applevision plugin for ocrmypdf then feed it to something like the archive-pdf-tools. Has anyone tried that workflow yet?

  23. MerlijnWajer commented on Jul 25, 2026

    @MerlijnWajer

    @beren12 I think something as suggested earlier in this thread (here: #541 (comment)) might work. I took a stab at that some years ago but IIRC there were still some rough edges if the input PDF has transparency and such (but that might not be a problem here): https://github.com/internetarchive/archive-pdf-tools/blob/master/bin/pdfcomp

    If you're interested in trying that we can chat either here or you can file an issue on archive-pdf-tools, and once pdfcomp works well enough for your use cases we can consider picking up the work to write a plugin for OCRmyPDF?

  24. rmast commented on Jul 25, 2026

    @rmast
  25. beren12 commented on Jul 26, 2026

    @beren12

    Yeah I've been trying to combine the 2 tools, @MerlijnWajer, but having issues. recode_pdf doesn't like the hocr from pdftotree sadly. The apple vision plugin @mast works well I am just trying to get the final pdf under 2M/page Are you on irc? I'm on liberachat and discord.

  26. MerlijnWajer commented on Jul 26, 2026

    @MerlijnWajer

    @beren12 pdfcomp uses pdf-to-hocr to create hOCR data from PDF text layers, so you should not need to use pdftotree: https://github.com/internetarchive/archive-pdf-tools/blob/master/bin/pdfcomp

  27. rmast commented on Jul 26, 2026

    @rmast
  28. MerlijnWajer commented on Jul 26, 2026

    @MerlijnWajer

    @beren12 - I missed your question about IRC, I am 'Wizzup' on libera chat in case you were asking me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions