简体   繁体   English

如何检查 Python 中的 PDF 页面是否着色?

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

I am having PDF that contains N number of pages.我有包含 N 页数的 PDF。 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.示例:如果我给 100 页 PDF 文件作为输入,它应该说 X 页是彩色的,y 页是非彩色的。

You could convert the PDF to images (eg with pdf2image) and then analyse the different channels.您可以将 PDF 转换为图像(例如使用 pdf2image),然后分析不同的通道。 For example using HSV the H and S channel should be 0 or near 0, if the page contains only black and white.例如,使用 HSV,如果页面仅包含黑白,则 H 和 S 通道应为 0 或接近 0。

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.给我 sw=1 和 color=1 例如 pdf 一个站点黑色文本和一侧红色文本,每个在白色背景上。

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 eg).如果背景不是全白且文本全黑(例如扫描的 PDF),您可能需要搜索小于部分像素的 hsv_sum[0:1]。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM