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

Revision 433, 4.1 kB (checked in by jerome, 17 years ago)

Now gives more information in case of failure.

  • 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 getPercentBW(img, nbpix) :
67    """Extracts the percents of Black from a picture, once converted to gray levels."""
68    if img.mode != "L" :
69        img = img.convert("L")
70    return { "B" : 100.0 - getPercent(img, nbpix)["L"] }
71   
72def getPercentRGB(img, nbpix) :
73    """Extracts the percents of Red, Green, Blue from a picture, once converted to RGB."""
74    if img.mode != "RGB" :
75        img = img.convert("RGB")
76    return getPercent(img, nbpix)   
77   
78def getPercentCMY(img, nbpix) :
79    """Extracts the percents of Cyan, Magenta, and Yellow from a picture once converted to RGB."""
80    result = getPercentRGB(img, nbpix)
81    return { "C" : 100.0 - result["R"],
82             "M" : 100.0 - result["G"],
83             "Y" : 100.0 - result["B"],
84           }
85   
86def getInkCoverage(fname, colorspace) :
87    """Returns a list of dictionnaries containing for each page,
88       for each color component, the percent of ink coverage on
89       that particular page.
90    """
91    result = []
92    colorspace = colorspace.upper()
93    computation = globals()["getPercent%s" % colorspace]
94    if colorspace == "CMYK" : # faster with psyco on my machine
95        try :
96            import psyco
97        except ImportError :   
98            pass
99        else :   
100            psyco.bind(computation)
101   
102    index = 0
103    try :
104        image = Image.open(fname)
105    except IOError, msg :   
106        raise pdlparser.PDLParserError, "%s (%s)" % (msg, fname)
107    else :   
108        try :
109            while 1 :
110                nbpixels = image.size[0] * image.size[1]
111                result.append(computation(image, nbpixels))
112                index += 1             
113                image.seek(index)
114        except EOFError :       
115            pass
116        return (colorspace, result)
117
118if __name__ == "__main__" :
119    # NB : length of result gives number of pages !
120    print getInkCoverage(sys.argv[1], "CMYK")
Note: See TracBrowser for help on using the browser.