PyPNM 1.12.1.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pypnm-1.12.1.2/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ This is free and unencumbered software released into the public domain.
2
+
3
+ Anyone is free to copy, modify, publish, use, compile, sell, or
4
+ distribute this software, either in source code form or as a compiled
5
+ binary, for any purpose, commercial or non-commercial, and by any
6
+ means.
7
+
8
+ In jurisdictions that recognize copyright laws, the author or authors
9
+ of this software dedicate any and all copyright interest in the
10
+ software to the public domain. We make this dedication for the benefit
11
+ of the public at large and to the detriment of our heirs and
12
+ successors. We intend this dedication to be an overt act of
13
+ relinquishment in perpetuity of all present and future rights to this
14
+ software under copyright law.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ For more information, please refer to <https://unlicense.org>
@@ -0,0 +1,91 @@
1
+ Metadata-Version: 2.1
2
+ Name: PyPNM
3
+ Version: 1.12.1.2
4
+ Summary: Reading and writing PPM and PGM image files, including 16 bits per channel.
5
+ Home-page: https://github.com/Dnyarri/PyPNM
6
+ Author: Ilya Razmanov
7
+ Author-email: ilyarazmanov@gmail.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: The Unlicense (Unlicense)
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Topic :: File Formats
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+
16
+ # PyPNM - PPM and PGM image files reading and writing
17
+
18
+ ## Justification and Overview
19
+
20
+ PPM and PGM (particular cases on PNM format group) are simplest file formats for RGB and L images, correspondingly. This simplicity lead to some consequences:
21
+
22
+ - lack of strict official specification. Instead, you may find words like "usual" in format description. Surely, there is someone who implement this part of image format in unprohibited, yet a totally unusual way.
23
+
24
+ - unwillingness of many software developers to provide any good support to for simple and open format. It took years for almighty Adobe Photoshop developers to include PNM module in distribution rather than count on third-party developers, and surely (see above) they used this chance to implement their own unusual separator scheme nobody else uses. What as to PNM support in Python, say, Pillow... sorry, I promised not to mention Pillow anywhere ladies and children are allowed to read it.
25
+
26
+ As a result, novice Python user (like me) may find it difficult to get reliable input/output modules for PPM and PGM image formats; therefore current PyPNM package was developed, combining input/output functions for 8-bits and 16-bits per channel binary and ascii PGM and PPM files, i.e. P2, P5, P3 and P6 PNM file types.
27
+
28
+ ## Target Image representation
29
+
30
+ Is seems logical to represent e.g. an RGB image as nested 3D structure - X, Y-sized matrix of three-component RGB vectors. Since in Python list seem to be about the only variant for mutable structures like that, it is suitable to represent image as list(list(list(int))) structure. Therefore, it would be convenient to have module read/write image data to/from such a structure.
31
+
32
+ ## pnmlpnm.py
33
+
34
+ Module **pnmlpnm.py** contains 100% pure Python implementation of everything one may need to read/write a variety of PGM and PPM files. I/O functions are written as functions/procedures, as simple as possible, and listed below:
35
+
36
+ - **pnm2list** - reading binary or ascii RGB PPM or L PGM file and returning image data as ints and nested list.
37
+ - **list2bin** - getting image data as ints and nested list and creating binary PPM (P6) or PGM (P5) data structure in memory. Suitable for generating data to display with Tkinter.
38
+ - **list2pnm** - writing data created with list2bin to file.
39
+ - **list2pnmascii** - alternative function to write ASCII PPM (P3) or PGM (P2) files.
40
+ - **create_image** - creating empty nested 3D list for image representation. Not used within this particular module but often needed by programs this module is supposed to be used with.
41
+
42
+ Detailed functions arguments description is provided below as well as in docstrings, but in general looks simple like that - you feed the function with your image data list and a filename, and get PNM file with that name written.
43
+
44
+ ### pnm2list
45
+
46
+ `X, Y, Z, maxcolors, image3D = pnmlpnm.pnm2list(in_filename)`
47
+
48
+ read data from PPM/PGM file, where:
49
+
50
+ - `X, Y, Z` - image sizes (int);
51
+ - `maxcolors` - number of colors per channel for current image (int);
52
+ - `image3D` - image pixel data as list(list(list(int)));
53
+ - `in_filename` - PPM/PGM file name (str).
54
+
55
+ ### list2bin
56
+
57
+ `image_bytes = pnmlpnm.list2bin(image3D, maxcolors)`
58
+
59
+ Convert nested image data list to PGM P5 or PPM P6 (binary) data structure in memory, where:
60
+
61
+ - `image3D` - `Y*X*Z` list (image) of lists (rows) of lists (pixels) of ints (channels);
62
+ - `maxcolors` - number of colors per channel for current image (int).
63
+ - `image_bytes` - PNM-structured binary data.
64
+
65
+ ### list2pnm
66
+
67
+ `pnmlpnm.list2pnm(out_filename, image3D, maxcolors)` where:
68
+
69
+ - `image3D` - `Y*X*Z` list (image) of lists (rows) of lists (pixels) of ints (channels);
70
+ - `maxcolors` - number of colors per channel for current image (int).
71
+ - `out_filename` - PNM file name.
72
+
73
+ ### list2pnmascii
74
+
75
+ Similar to `list2pnm` above but creates ascii pnm file instead of binary.
76
+
77
+ `pnmlpnm.list2pnmascii(out_filename, image3D, maxcolors)` where:
78
+
79
+ - `image3D` - `Y*X*Z` list (image) of lists (rows) of lists (pixels) of ints (channels);
80
+ - `maxcolors` - number of colors per channel for current image (int).
81
+ - `out_filename` - PNM file name.
82
+
83
+ ### create_image
84
+
85
+ Create empty 3D nested list of `X*Y*Z` sizes.
86
+
87
+ ### References
88
+
89
+ [Netpbm file formats description](https://netpbm.sourceforge.net/doc/)
90
+
91
+ [PyPNM page](https://dnyarri.github.io/pypnm.html) - contains example application of using `list2bin` to produce data for Tkinter `PhotoImage(data=...)` to display.
@@ -0,0 +1,91 @@
1
+ Metadata-Version: 2.1
2
+ Name: PyPNM
3
+ Version: 1.12.1.2
4
+ Summary: Reading and writing PPM and PGM image files, including 16 bits per channel.
5
+ Home-page: https://github.com/Dnyarri/PyPNM
6
+ Author: Ilya Razmanov
7
+ Author-email: ilyarazmanov@gmail.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: The Unlicense (Unlicense)
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Topic :: File Formats
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+
16
+ # PyPNM - PPM and PGM image files reading and writing
17
+
18
+ ## Justification and Overview
19
+
20
+ PPM and PGM (particular cases on PNM format group) are simplest file formats for RGB and L images, correspondingly. This simplicity lead to some consequences:
21
+
22
+ - lack of strict official specification. Instead, you may find words like "usual" in format description. Surely, there is someone who implement this part of image format in unprohibited, yet a totally unusual way.
23
+
24
+ - unwillingness of many software developers to provide any good support to for simple and open format. It took years for almighty Adobe Photoshop developers to include PNM module in distribution rather than count on third-party developers, and surely (see above) they used this chance to implement their own unusual separator scheme nobody else uses. What as to PNM support in Python, say, Pillow... sorry, I promised not to mention Pillow anywhere ladies and children are allowed to read it.
25
+
26
+ As a result, novice Python user (like me) may find it difficult to get reliable input/output modules for PPM and PGM image formats; therefore current PyPNM package was developed, combining input/output functions for 8-bits and 16-bits per channel binary and ascii PGM and PPM files, i.e. P2, P5, P3 and P6 PNM file types.
27
+
28
+ ## Target Image representation
29
+
30
+ Is seems logical to represent e.g. an RGB image as nested 3D structure - X, Y-sized matrix of three-component RGB vectors. Since in Python list seem to be about the only variant for mutable structures like that, it is suitable to represent image as list(list(list(int))) structure. Therefore, it would be convenient to have module read/write image data to/from such a structure.
31
+
32
+ ## pnmlpnm.py
33
+
34
+ Module **pnmlpnm.py** contains 100% pure Python implementation of everything one may need to read/write a variety of PGM and PPM files. I/O functions are written as functions/procedures, as simple as possible, and listed below:
35
+
36
+ - **pnm2list** - reading binary or ascii RGB PPM or L PGM file and returning image data as ints and nested list.
37
+ - **list2bin** - getting image data as ints and nested list and creating binary PPM (P6) or PGM (P5) data structure in memory. Suitable for generating data to display with Tkinter.
38
+ - **list2pnm** - writing data created with list2bin to file.
39
+ - **list2pnmascii** - alternative function to write ASCII PPM (P3) or PGM (P2) files.
40
+ - **create_image** - creating empty nested 3D list for image representation. Not used within this particular module but often needed by programs this module is supposed to be used with.
41
+
42
+ Detailed functions arguments description is provided below as well as in docstrings, but in general looks simple like that - you feed the function with your image data list and a filename, and get PNM file with that name written.
43
+
44
+ ### pnm2list
45
+
46
+ `X, Y, Z, maxcolors, image3D = pnmlpnm.pnm2list(in_filename)`
47
+
48
+ read data from PPM/PGM file, where:
49
+
50
+ - `X, Y, Z` - image sizes (int);
51
+ - `maxcolors` - number of colors per channel for current image (int);
52
+ - `image3D` - image pixel data as list(list(list(int)));
53
+ - `in_filename` - PPM/PGM file name (str).
54
+
55
+ ### list2bin
56
+
57
+ `image_bytes = pnmlpnm.list2bin(image3D, maxcolors)`
58
+
59
+ Convert nested image data list to PGM P5 or PPM P6 (binary) data structure in memory, where:
60
+
61
+ - `image3D` - `Y*X*Z` list (image) of lists (rows) of lists (pixels) of ints (channels);
62
+ - `maxcolors` - number of colors per channel for current image (int).
63
+ - `image_bytes` - PNM-structured binary data.
64
+
65
+ ### list2pnm
66
+
67
+ `pnmlpnm.list2pnm(out_filename, image3D, maxcolors)` where:
68
+
69
+ - `image3D` - `Y*X*Z` list (image) of lists (rows) of lists (pixels) of ints (channels);
70
+ - `maxcolors` - number of colors per channel for current image (int).
71
+ - `out_filename` - PNM file name.
72
+
73
+ ### list2pnmascii
74
+
75
+ Similar to `list2pnm` above but creates ascii pnm file instead of binary.
76
+
77
+ `pnmlpnm.list2pnmascii(out_filename, image3D, maxcolors)` where:
78
+
79
+ - `image3D` - `Y*X*Z` list (image) of lists (rows) of lists (pixels) of ints (channels);
80
+ - `maxcolors` - number of colors per channel for current image (int).
81
+ - `out_filename` - PNM file name.
82
+
83
+ ### create_image
84
+
85
+ Create empty 3D nested list of `X*Y*Z` sizes.
86
+
87
+ ### References
88
+
89
+ [Netpbm file formats description](https://netpbm.sourceforge.net/doc/)
90
+
91
+ [PyPNM page](https://dnyarri.github.io/pypnm.html) - contains example application of using `list2bin` to produce data for Tkinter `PhotoImage(data=...)` to display.
@@ -0,0 +1,9 @@
1
+ LICENSE
2
+ README.md
3
+ setup.py
4
+ PyPNM.egg-info/PKG-INFO
5
+ PyPNM.egg-info/SOURCES.txt
6
+ PyPNM.egg-info/dependency_links.txt
7
+ PyPNM.egg-info/top_level.txt
8
+ pypnm/__init__.py
9
+ pypnm/pnmlpnm.py
@@ -0,0 +1 @@
1
+ pypnm
@@ -0,0 +1,76 @@
1
+ # PyPNM - PPM and PGM image files reading and writing
2
+
3
+ ## Justification and Overview
4
+
5
+ PPM and PGM (particular cases on PNM format group) are simplest file formats for RGB and L images, correspondingly. This simplicity lead to some consequences:
6
+
7
+ - lack of strict official specification. Instead, you may find words like "usual" in format description. Surely, there is someone who implement this part of image format in unprohibited, yet a totally unusual way.
8
+
9
+ - unwillingness of many software developers to provide any good support to for simple and open format. It took years for almighty Adobe Photoshop developers to include PNM module in distribution rather than count on third-party developers, and surely (see above) they used this chance to implement their own unusual separator scheme nobody else uses. What as to PNM support in Python, say, Pillow... sorry, I promised not to mention Pillow anywhere ladies and children are allowed to read it.
10
+
11
+ As a result, novice Python user (like me) may find it difficult to get reliable input/output modules for PPM and PGM image formats; therefore current PyPNM package was developed, combining input/output functions for 8-bits and 16-bits per channel binary and ascii PGM and PPM files, i.e. P2, P5, P3 and P6 PNM file types.
12
+
13
+ ## Target Image representation
14
+
15
+ Is seems logical to represent e.g. an RGB image as nested 3D structure - X, Y-sized matrix of three-component RGB vectors. Since in Python list seem to be about the only variant for mutable structures like that, it is suitable to represent image as list(list(list(int))) structure. Therefore, it would be convenient to have module read/write image data to/from such a structure.
16
+
17
+ ## pnmlpnm.py
18
+
19
+ Module **pnmlpnm.py** contains 100% pure Python implementation of everything one may need to read/write a variety of PGM and PPM files. I/O functions are written as functions/procedures, as simple as possible, and listed below:
20
+
21
+ - **pnm2list** - reading binary or ascii RGB PPM or L PGM file and returning image data as ints and nested list.
22
+ - **list2bin** - getting image data as ints and nested list and creating binary PPM (P6) or PGM (P5) data structure in memory. Suitable for generating data to display with Tkinter.
23
+ - **list2pnm** - writing data created with list2bin to file.
24
+ - **list2pnmascii** - alternative function to write ASCII PPM (P3) or PGM (P2) files.
25
+ - **create_image** - creating empty nested 3D list for image representation. Not used within this particular module but often needed by programs this module is supposed to be used with.
26
+
27
+ Detailed functions arguments description is provided below as well as in docstrings, but in general looks simple like that - you feed the function with your image data list and a filename, and get PNM file with that name written.
28
+
29
+ ### pnm2list
30
+
31
+ `X, Y, Z, maxcolors, image3D = pnmlpnm.pnm2list(in_filename)`
32
+
33
+ read data from PPM/PGM file, where:
34
+
35
+ - `X, Y, Z` - image sizes (int);
36
+ - `maxcolors` - number of colors per channel for current image (int);
37
+ - `image3D` - image pixel data as list(list(list(int)));
38
+ - `in_filename` - PPM/PGM file name (str).
39
+
40
+ ### list2bin
41
+
42
+ `image_bytes = pnmlpnm.list2bin(image3D, maxcolors)`
43
+
44
+ Convert nested image data list to PGM P5 or PPM P6 (binary) data structure in memory, where:
45
+
46
+ - `image3D` - `Y*X*Z` list (image) of lists (rows) of lists (pixels) of ints (channels);
47
+ - `maxcolors` - number of colors per channel for current image (int).
48
+ - `image_bytes` - PNM-structured binary data.
49
+
50
+ ### list2pnm
51
+
52
+ `pnmlpnm.list2pnm(out_filename, image3D, maxcolors)` where:
53
+
54
+ - `image3D` - `Y*X*Z` list (image) of lists (rows) of lists (pixels) of ints (channels);
55
+ - `maxcolors` - number of colors per channel for current image (int).
56
+ - `out_filename` - PNM file name.
57
+
58
+ ### list2pnmascii
59
+
60
+ Similar to `list2pnm` above but creates ascii pnm file instead of binary.
61
+
62
+ `pnmlpnm.list2pnmascii(out_filename, image3D, maxcolors)` where:
63
+
64
+ - `image3D` - `Y*X*Z` list (image) of lists (rows) of lists (pixels) of ints (channels);
65
+ - `maxcolors` - number of colors per channel for current image (int).
66
+ - `out_filename` - PNM file name.
67
+
68
+ ### create_image
69
+
70
+ Create empty 3D nested list of `X*Y*Z` sizes.
71
+
72
+ ### References
73
+
74
+ [Netpbm file formats description](https://netpbm.sourceforge.net/doc/)
75
+
76
+ [PyPNM page](https://dnyarri.github.io/pypnm.html) - contains example application of using `list2bin` to produce data for Tkinter `PhotoImage(data=...)` to display.
File without changes
@@ -0,0 +1,366 @@
1
+ #!/usr/bin/env python3
2
+
3
+ """Functions to read PPM and PGM files to nested 3D list and write back.
4
+
5
+ Overview
6
+ ----------
7
+
8
+ pnmlpnm (pnm-list-pnm) is a pack of functions for dealing with PPM and PGM image files. Functions included are:
9
+
10
+ - pnm2list - reading binary or ascii RGB PPM or L PGM file and returning image data as ints and nested list.
11
+ - list2bin - getting image data as ints and nested list and creating binary PPM (P6) or PGM (P5) data structure in memory. Suitable for generating data to display with Tkinter.
12
+ - list2pnm - writing data created with list2bin to file.
13
+ - list2pnmascii - alternative function to write ASCII PPM (P3) or PGM (P2) files.
14
+ - create_image - creating empty nested 3D list for image representation. Not used within this particular module but often needed by programs this module is supposed to be used with.
15
+
16
+ Installation
17
+ --------------
18
+ Simply put module into your main program folder.
19
+
20
+ Usage
21
+ -------
22
+ After ``import pnmlpnm``, use something like
23
+
24
+ ``X, Y, Z, maxcolors, image3D = pnmlpnm.pnm2list(in_filename)``
25
+
26
+ for reading data from PPM/PGM, where:
27
+
28
+ - X, Y, Z - image sizes (int);
29
+ - maxcolors - number of colors per channel for current image (int);
30
+ - image3D - image pixel data as list(list(list(int)));
31
+
32
+ and
33
+
34
+ ``pnmlpnm.pnm = list2bin(image3D, maxcolors)``
35
+
36
+ for writing data from image3D nested list to "pnm" bytes object in memory,
37
+
38
+ or
39
+
40
+ ``pnmlpnm.list2pnm(out_filename, image3D, maxcolors)``
41
+
42
+ or
43
+
44
+ ``pnmlpnm.list2pnmascii(out_filename, image3D, maxcolors)``
45
+
46
+ for writing data from image3D nested list to PPM/PGM file "out_filename".
47
+
48
+
49
+ Copyright and redistribution
50
+ -----------------------------
51
+ Written by Ilya Razmanov (https://dnyarri.github.io/) to provide working with PPM/PGM files and creating PPM data to be displayed with Tkinter "PhotoImage" class.
52
+
53
+ May be freely used and redistributed.
54
+
55
+ References
56
+ -----------------------------
57
+
58
+ Netpbm specs: https://netpbm.sourceforge.net/doc/
59
+
60
+ History:
61
+ ----------
62
+
63
+ 0.11.26.0 Initial working version 26 Nov 2024.
64
+
65
+ 0.11.27.3 Implemented fix for Adobe Photoshop CS6 using linebreaks in header.
66
+
67
+ 0.11.28.0 Rewritten to use less arguments for output; X, Y, Z autodetected.
68
+
69
+ 0.11.29.0 Added ASCII write support.
70
+
71
+ 0.11.30.0 Switched to array; this allowed 16 bpc P5 and P6 files writing.
72
+
73
+ 0.11.30.2 Seems like finally fixed 16 bpc P5 and P6 files reading. Looks ugly but works.
74
+
75
+ 1.12.1.2 Seem to be ready for release.
76
+
77
+ """
78
+
79
+ __author__ = 'Ilya Razmanov'
80
+ __copyright__ = '(c) 2024 Ilya Razmanov'
81
+ __credits__ = 'Ilya Razmanov'
82
+ __license__ = 'unlicense'
83
+ __version__ = '1.12.1.2'
84
+ __maintainer__ = 'Ilya Razmanov'
85
+ __email__ = 'ilyarazmanov@gmail.com'
86
+ __status__ = 'Production'
87
+
88
+ import array
89
+
90
+ ''' ╔══════════╗
91
+ ║ pnm2list ║
92
+ ╚══════════╝ '''
93
+
94
+ def pnm2list(filename: str) -> tuple[int, int, int, int, list[list[list[int]]]]:
95
+ """Read PGM or PPM file to nested image data list.
96
+
97
+ Usage:
98
+
99
+ ``X, Y, Z, maxcolors, image3D = pnmlpnm.pnm2list(in_filename)``
100
+
101
+ for reading data from PPM/PGM, where:
102
+
103
+ - X, Y, Z - image sizes (int);
104
+ - maxcolors - number of colors per channel for current image (int);
105
+ - image3D - image pixel data as list(list(list(int)));
106
+ - in_filename - PPM/PGM file name (str).
107
+
108
+ """
109
+
110
+ with open(filename, 'rb') as file: # Open file in binary mode
111
+ magic = file.readline().strip().decode()
112
+
113
+ # Passing comments by
114
+ comment_line = file.readline().decode()
115
+ while comment_line.startswith('#'):
116
+ comment_line = file.readline().decode()
117
+
118
+ # Reading dimensions. Photoshop CS6 uses EOLN as separator, GIMP, XnView etc. use space
119
+ size_temp = comment_line.split()
120
+ if len(size_temp) < 2: # Part for Photoshop
121
+ X = int(size_temp[0])
122
+ Y = int(file.readline().decode())
123
+ else: # Part for most other software
124
+ X, Y = map(int, comment_line.split())
125
+
126
+ # Color depth
127
+ maxcolors = int(file.readline().strip().decode())
128
+
129
+ ''' ┌─────┐
130
+ │ RGB │
131
+ └────-┘ '''
132
+
133
+ if magic == 'P6': # RGB bin
134
+ Z = 3
135
+ list_3d = []
136
+ for _ in range(Y):
137
+ row = []
138
+ for _ in range(X):
139
+
140
+ if maxcolors < 256:
141
+ red = int.from_bytes(file.read(1))
142
+ green = int.from_bytes(file.read(1))
143
+ blue = int.from_bytes(file.read(1))
144
+ else:
145
+ red = int.from_bytes(file.read(2))
146
+ green = int.from_bytes(file.read(2))
147
+ blue = int.from_bytes(file.read(2))
148
+
149
+ row.append([red, green, blue])
150
+ list_3d.append(row)
151
+
152
+ if magic == 'P3': # RGB ascii
153
+ Z = 3
154
+
155
+ list_1d = [] # Toss everything to 1D list because linebreaks in PNM are unpredictable
156
+ for _ in range(Y * X * Z): # Y*X*Z most likely excessive but should cover any formatting
157
+ pixel_data = file.readline().split()
158
+ list_1d.extend(map(int, pixel_data)) # Extend to kill all formatting perversions.
159
+
160
+ list_3d = [ # Now break 1D toss into component compounds, building 3D list
161
+ [
162
+ [
163
+ list_1d[z + x * Z + y * X * Z] for z in range(Z)
164
+ ] for x in range(X)
165
+ ] for y in range(Y)
166
+ ]
167
+
168
+ ''' ┌───┐
169
+ │ L │
170
+ └───┘ '''
171
+
172
+ if magic == 'P5': # L bin
173
+ Z = 1
174
+ list_3d = []
175
+ for _ in range(Y):
176
+ row = []
177
+ for _ in range(X):
178
+ if maxcolors < 256:
179
+ channel = [int.from_bytes(file.read(1))]
180
+ else:
181
+ channel = [int.from_bytes(file.read(2))]
182
+ row.append(channel)
183
+ list_3d.append(row)
184
+
185
+ if magic == 'P2': # L ascii
186
+ Z = 1
187
+
188
+ list_1d = [] # Toss everything to 1D list because linebreaks in ASCII PGM are unpredictable
189
+ for _ in range(Y * X * Z):
190
+ pixel_data = file.readline().split()
191
+ list_1d.extend(map(int, pixel_data))
192
+
193
+ list_3d = [ # Now break 1D toss into component compounds, building 3D list
194
+ [
195
+ [
196
+ list_1d[z + x * Z + y * X * Z] for z in range(Z)
197
+ ] for x in range(X)
198
+ ] for y in range(Y)
199
+ ]
200
+
201
+ return (X, Y, Z, maxcolors, list_3d) # Output mimic that of pnglpng
202
+
203
+
204
+ ''' ╔══════════╗
205
+ ║ list2bin ║
206
+ ╚══════════╝ '''
207
+
208
+ def list2bin(in_list_3d: list[list[list[int]]], maxcolors: int) -> bytes:
209
+ """Convert nested image data list to PGM P5 or PPM P6 (binary) data structure in memory.
210
+
211
+ Based on Netpbm specs at https://netpbm.sourceforge.net/doc/
212
+
213
+ For LA and RGBA images A channel is deleted.
214
+
215
+ Usage:
216
+
217
+ ``image_bytes = pnmlpnm.list2bin(image3D, maxcolors)`` where:
218
+
219
+ - ``image3D`` - Y*X*Z list (image) of lists (rows) of lists (pixels) of ints (channels);
220
+ - ``maxcolors`` - number of colors per channel for current image (int).
221
+
222
+ Output:
223
+
224
+ - ``image_bytes`` - PNM-structured binary data.
225
+
226
+ """
227
+
228
+ # Determining list sizes
229
+ Y = len(in_list_3d)
230
+ X = len(in_list_3d[0])
231
+ Z = len(in_list_3d[0][0])
232
+
233
+ # Flattening 3D list to 1D list
234
+ in_list_1d = [c for row in in_list_3d for px in row for c in px]
235
+
236
+ if Z == 1: # L image
237
+ magic = 'P5'
238
+
239
+ if Z == 2: # LA image
240
+ magic = 'P5'
241
+ del in_list_1d[1::2] # Deleting A channel
242
+
243
+ if Z == 3: # RGB image
244
+ magic = 'P6'
245
+
246
+ if Z == 4: # RGBA image
247
+ magic = 'P6'
248
+ del in_list_1d[3::4] # Deleting A channel
249
+
250
+ if maxcolors < 256:
251
+ datatype = 'B'
252
+ else:
253
+ datatype = 'H'
254
+
255
+ header = array.array('B', f'{magic}\n{X} {Y}\n{maxcolors}\n'.encode())
256
+ content = array.array(datatype, in_list_1d)
257
+
258
+ content.byteswap() # Critical!
259
+
260
+ pnm = header.tobytes() + content.tobytes()
261
+
262
+ return pnm # End of "list2bin" list to PNM conversion function
263
+
264
+
265
+ ''' ╔══════════╗
266
+ ║ list2pnm ║
267
+ ╚══════════╝ '''
268
+
269
+ def list2pnm(out_filename: str, in_list_3d: list[list[list[int]]], maxcolors: int) -> None:
270
+ """Write PNM data structure as produced with ``list2bin`` to ``out_filename`` file.
271
+
272
+ Usage:
273
+
274
+ ``pnmlpnm.list2pnm(out_filename, image3D, maxcolors)`` where:
275
+
276
+ - ``image3D`` - Y*X*Z list (image) of lists (rows) of lists (pixels) of ints (channels);
277
+ - ``maxcolors`` - number of colors per channel for current image (int).
278
+
279
+ Output:
280
+
281
+ - ``out_filename`` - PNM file name.
282
+
283
+
284
+ """
285
+
286
+ pnm = list2bin(in_list_3d, maxcolors)
287
+
288
+ with open(out_filename, 'wb') as file_pnm: # write pnm bin structure obtained above to file
289
+ file_pnm.write(pnm)
290
+
291
+ return None # End of "list2pnm" function for writing "list2bin" output as file
292
+
293
+
294
+ ''' ╔═══════════════╗
295
+ ║ list2pnmascii ║
296
+ ╚═══════════════╝ '''
297
+
298
+ def list2pnmascii(out_filename: str, in_list_3d: list[list[list[int]]], maxcolors: int) -> None:
299
+ """Write ASCII PNM ``out_filename`` file.
300
+
301
+ Usage:
302
+
303
+ ``pnmlpnm.list2pnmascii(out_filename, image3D, maxcolors)`` where:
304
+
305
+ - ``image3D`` - Y*X*Z list (image) of lists (rows) of lists (pixels) of ints (channels);
306
+ - ``maxcolors`` - number of colors per channel for current image (int).
307
+
308
+ Output:
309
+
310
+ - ``out_filename`` - PNM file name.
311
+
312
+ """
313
+
314
+ # Determining list sizes
315
+ Y = len(in_list_3d)
316
+ X = len(in_list_3d[0])
317
+ Z = len(in_list_3d[0][0])
318
+
319
+ # Flattening 3D list to 1D list
320
+ in_list_1d = [c for row in in_list_3d for px in row for c in px]
321
+
322
+ if Z == 1: # L image
323
+ magic = 'P2'
324
+
325
+ if Z == 2: # LA image
326
+ magic = 'P2'
327
+ del in_list_1d[1::2] # Deleting A channel
328
+
329
+ if Z == 3: # RGB image
330
+ magic = 'P3'
331
+
332
+ if Z == 4: # RGBA image
333
+ magic = 'P3'
334
+ del in_list_1d[3::4] # Deleting A channel
335
+
336
+ in_str_1d = ' '.join([str(c) for c in in_list_1d]) # Turning list to string
337
+
338
+ with open(out_filename, 'w') as file_pnm: # write pnm string structure obtained above to file
339
+ file_pnm.write(f'{magic}\n{X} {Y}\n{maxcolors}\n')
340
+ file_pnm.write(in_str_1d)
341
+
342
+ return None # End of "list2pnmascii" function for writing ASCII PPM/PGM file
343
+
344
+
345
+ ''' ╔════════════════════╗
346
+ ║ Create empty image ║
347
+ ╚════════════════════╝ '''
348
+
349
+ def create_image(X: int, Y: int, Z: int) -> list[list[list[int]]]:
350
+ """Create empty 3D nested list of X*Y*Z sizes."""
351
+
352
+ new_image = [
353
+ [
354
+ [
355
+ 0 for z in range(Z)
356
+ ] for x in range(X)
357
+ ] for y in range(Y)
358
+ ]
359
+
360
+ return new_image # End of "create_image" empty nested 3D list creation
361
+
362
+
363
+ # --------------------------------------------------------------
364
+
365
+ if __name__ == '__main__':
366
+ print('Module to be imported, not run as standalone')
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,23 @@
1
+ import setuptools
2
+
3
+ with open("README.md") as file:
4
+ read_me_description = file.read()
5
+
6
+ setuptools.setup(
7
+ name="PyPNM",
8
+ version="1.12.1.2",
9
+ author="Ilya Razmanov",
10
+ author_email="ilyarazmanov@gmail.com",
11
+ description="Reading and writing PPM and PGM image files, including 16 bits per channel.",
12
+ long_description=read_me_description,
13
+ long_description_content_type="text/markdown",
14
+ url="https://github.com/Dnyarri/PyPNM",
15
+ packages=['pypnm'],
16
+ classifiers=[
17
+ "Programming Language :: Python :: 3",
18
+ "License :: OSI Approved :: The Unlicense (Unlicense)",
19
+ "Operating System :: OS Independent",
20
+ "Topic :: File Formats"
21
+ ],
22
+ python_requires='>=3.10',
23
+ )