root / pkpgcounter / trunk / pkpgpdls / inkcoverage.py @ 439

Revision 439, 4.4 kB (checked in by jerome, 17 years ago)

Now recognizes the GC pseudo colorspace to differentiate
between grayscale and coloured pages.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Revision Id
Line 
1#! /usr/bin/env python
2# -*- coding: ISO-8859-15 -*-
3#
4# pkpgcounter : a generic Page Description Language parser
5#
6# (c) 2003, 2004, 2005, 2006 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20#
21# $Id$
22#
23
24"""This modules implements the computation of ink coverage in different colorspaces."""
25
26import sys
27
28from PIL import Image
29
30import pdlparser
31
32def getPercent(img, nbpix) :
33    """Extracts the percents per color component from a picture.
34     
35       Faster without Psyco on my own machine.
36    """
37    result = {}     
38    bands = img.split()
39    for (i, bandname) in enumerate(img.getbands()) :
40        result[bandname] = 100.0 * (reduce(lambda current, next: current + (next[1] * next[0]), enumerate(bands[i].histogram()), 0) / 255.0) / nbpix
41    return result   
42   
43def getPercentCMYK(img, nbpix) :
44    """Extracts the percents of Cyan, Magenta, Yellow, and Black from a picture.
45     
46       PIL doesn't produce useable CMYK for our algorithm, so we use the algorithm from PrintBill.
47       Psyco speeds this function up by around 2.5 times on my computer.
48    """
49    if img.mode != "RGB" :
50        img = img.convert("RGB")
51    data = img.getdata()   
52    cyan = magenta = yellow = black = 0   
53    for (r, g, b) in data :
54        if r == g == b :
55            black += 255 - r
56        else :   
57            cyan += 255 - r
58            magenta += 255 - g
59            yellow += 255 - b
60    return { "C" : 100.0 * (cyan / 255.0) / nbpix,
61             "M" : 100.0 * (magenta / 255.0) / nbpix,
62             "Y" : 100.0 * (yellow / 255.0) / nbpix,
63             "K" : 100.0 * (black / 255.0) / nbpix,
64           }
65       
66def getPercentGC(img, nbpix) :       
67    """Determines if a page is in grayscale or colour mode."""
68    result = getPercentCMYK(img, nbpix)
69    if result["C"] == result["M"] == result["Y"] == 0.0 :
70        return { "G" : 100.0, "C" : 0.0 }
71    else :   
72        return { "G" : 0.0, "C" : 100.0 }
73   
74def getPercentBW(img, nbpix) :
75    """Extracts the percents of Black from a picture, once converted to gray levels."""
76    if img.mode != "L" :
77        img = img.convert("L")
78    return { "B" : 100.0 - getPercent(img, nbpix)["L"] }
79   
80def getPercentRGB(img, nbpix) :
81    """Extracts the percents of Red, Green, Blue from a picture, once converted to RGB."""
82    if img.mode != "RGB" :
83        img = img.convert("RGB")
84    return getPercent(img, nbpix)   
85   
86def getPercentCMY(img, nbpix) :
87    """Extracts the percents of Cyan, Magenta, and Yellow from a picture once converted to RGB."""
88    result = getPercentRGB(img, nbpix)
89    return { "C" : 100.0 - result["R"],
90             "M" : 100.0 - result["G"],
91             "Y" : 100.0 - result["B"],
92           }
93   
94def getInkCoverage(fname, colorspace) :
95    """Returns a list of dictionnaries containing for each page,
96       for each color component, the percent of ink coverage on
97       that particular page.
98    """
99    result = []
100    colorspace = colorspace.upper()
101    computation = globals()["getPercent%s" % colorspace]
102    if colorspace in ("CMYK", "GC") : # faster with psyco on my machine
103        try :
104            import psyco
105        except ImportError :   
106            pass
107        else :   
108            psyco.bind(getPercentCMYK)
109   
110    index = 0
111    try :
112        image = Image.open(fname)
113    except IOError, msg :   
114        raise pdlparser.PDLParserError, "%s (%s)" % (msg, fname)
115    else :   
116        try :
117            while 1 :
118                nbpixels = image.size[0] * image.size[1]
119                result.append(computation(image, nbpixels))
120                index += 1             
121                image.seek(index)
122        except EOFError :       
123            pass
124        return (colorspace, result)
125
126if __name__ == "__main__" :
127    # NB : length of result gives number of pages !
128    print getInkCoverage(sys.argv[1], "CMYK")
Note: See TracBrowser for help on using the browser.