How to check the PDF page is coloured or not in Python?

Viewed 585

I am having PDF that contains N number of pages. How can I count the coloured and non-coloured(Black and white) pages.

Example : If I give 100 pages PDF file as input, it should say X number of pages are coloured and y number of pages are non-coloured.

1 Answers

You could convert the PDF to images (e.g. with pdf2image) and then analyse the different channels. For example using HSV the H and S channel should be 0 or near 0, if the page contains only black and white.

import pdf2image
import numpy as np

images = convert_from_path('example.pdf')
sw=0
color=0
for image in images:
    img = np.array(image.convert('HSV'))
    hsv_sum = img.sum(0).sum(0)
    if hsv_sum[0] == 0 and hsv_sum[1] == 0:
        sw += 1
    else:
        color += 1

Gives me sw=1 and color=1 for an example pdf with one site black text and one side red text, each on white background.

You may need to search for hsv_sum[0:1] smaller than a portion of pixels, if the background is not completely white and the text completely black (scanned PDFs e.g.).

Related