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

Revision 279, 2.2 kB (checked in by jerome, 18 years ago)

Now extracts black as well. For black the result is identical
to PrintBill?'s one when parsing the same 8-bit gray png images,
although my own code accepts other formats.

  • 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 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
24import sys
25
26from PIL import Image
27
28""" RGB to CMYK formula :
29
30        Black = min(1 - r, 1 - g, 1 - b)
31        Cyan = (1 - r - Black) / (1 - Black)
32        Magenta = (1 - g - Black) / (1 - Black)
33        Yellow = (1 - b - Black) / (1 - Black)
34"""       
35
36def getPercentCMY(img, nbpix) :
37    result = []
38    (r, g, b) = [ p.histogram() for p in img.split() ]
39    for colorhisto in (r, g, b) :
40        result.append(100.0 * (reduce(lambda current, next: current + (next[1] * (255 - next[0])), enumerate(colorhisto), 0) / 255.0) / nbpix)
41    return tuple(result)
42   
43def getPercentBlack(img, nbpix) :
44    if img.mode != "L" :
45        img = img.convert("L")
46    return 100.0 * (reduce(lambda current, next: current + (next[1] * (255 - next[0])), enumerate(img.histogram()[:-1]), 0) / 255.0) / nbpix
47   
48def getPercents(fname) :
49    """Extracts the ink percentages from an image."""
50    image = Image.open(fname)
51    nbpixels = image.size[0] * image.size[1]
52    result = {}
53    try :
54        result["black"] = getPercentBlack(image, nbpixels)
55    except :     
56        sys.stderr.write("Problem when extracting BLACK !\n")
57    try :   
58        result["cmy"] = getPercentCMY(image, nbpixels)
59    except :     
60        sys.stderr.write("Problem when extracting CMY !\n")
61    return result
62
63if __name__ == "__main__" :
64    print getPercents(sys.argv[1])
Note: See TracBrowser for help on using the browser.