-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpgm.go
502 lines (448 loc) · 14.2 KB
/
pgm.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
// This file provides image support for both "raw" (binary) and
// "plain" (ASCII) Portable GrayMap (PGM) files.
package netpbm
import (
"bufio"
"errors"
"fmt"
"image"
"image/color"
"io"
"strings"
"github.com/spakin/netpbm/npcolor"
)
// GrayM is an in-memory image whose At method returns npcolor.GrayM values.
type GrayM struct {
// Pix holds the image's pixels as gray values. The pixel at (x, y)
// starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*1].
Pix []uint8
// Stride is the Pix stride (in bytes) between vertically adjacent pixels.
Stride int
// Rect is the image's bounds.
Rect image.Rectangle
// Model is the image's color model.
Model npcolor.GrayMModel
}
// ColorModel returns the GrayM image's color model.
func (p *GrayM) ColorModel() color.Model { return p.Model }
// Bounds returns the domain for which At can return non-zero color. The
// bounds do not necessarily contain the point (0, 0).
func (p *GrayM) Bounds() image.Rectangle { return p.Rect }
// At returns the color of the pixel at (x, y) as a color.Color.
// At(Bounds().Min.X, Bounds().Min.Y) returns the upper-left pixel of the grid.
// At(Bounds().Max.X-1, Bounds().Max.Y-1) returns the lower-right one.
func (p *GrayM) At(x, y int) color.Color {
return p.GrayMAt(x, y)
}
// GrayMAt returns the color of the pixel at (x, y) as an npcolor.GrayM.
func (p *GrayM) GrayMAt(x, y int) npcolor.GrayM {
if !(image.Point{x, y}.In(p.Rect)) {
return npcolor.GrayM{}
}
i := p.PixOffset(x, y)
return npcolor.GrayM{Y: p.Pix[i], M: p.Model.M}
}
// PixOffset returns the index of the first element of Pix that corresponds to
// the pixel at (x, y).
func (p *GrayM) PixOffset(x, y int) int {
return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*1
}
// Set sets the pixel at (x, y) to a given color, expressed as a color.Color.
func (p *GrayM) Set(x, y int, c color.Color) {
if !(image.Point{x, y}.In(p.Rect)) {
return
}
i := p.PixOffset(x, y)
p.Pix[i] = p.Model.Convert(c).(npcolor.GrayM).Y
}
// SetGrayM sets the pixel at (x, y) to a given color, expressed as an
// npcolor.GrayM.
func (p *GrayM) SetGrayM(x, y int, c npcolor.GrayM) {
if !(image.Point{x, y}.In(p.Rect)) {
return
}
i := p.PixOffset(x, y)
if c.M == p.Model.M {
p.Pix[i] = c.Y
} else {
p.Set(x, y, c)
}
}
// SubImage returns an image representing the portion of the image p visible
// through r. The returned value shares pixels with the original image.
func (p *GrayM) SubImage(r image.Rectangle) image.Image {
r = r.Intersect(p.Rect)
// If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to
// be inside either r1 or r2 if the intersection is empty. Without
// explicitly checking for this, the Pix[i:] expression below can
// panic.
if r.Empty() {
return &GrayM{}
}
i := p.PixOffset(r.Min.X, r.Min.Y)
return &GrayM{
Pix: p.Pix[i:],
Stride: p.Stride,
Rect: r,
}
}
// Opaque scans the entire image and reports whether it is fully opaque.
func (p *GrayM) Opaque() bool {
return true
}
// MaxValue returns the maximum grayscale value allowed.
func (p *GrayM) MaxValue() uint16 {
return uint16(p.Model.M)
}
// Format identifies the image as a PGM image.
func (p *GrayM) Format() Format {
return PGM
}
// HasAlpha indicates that there is no alpha channel.
func (p *GrayM) HasAlpha() bool {
return false
}
// PromoteToRGBM generates an 8-bit color image that looks identical to
// the given grayscale image.
func (p *GrayM) PromoteToRGBM() *RGBM {
rgb := NewRGBM(p.Bounds(), p.Model.M)
for i, g := range p.Pix {
rgb.Pix[i*3+0] = g
rgb.Pix[i*3+1] = g
rgb.Pix[i*3+2] = g
}
return rgb
}
// NewGrayM returns a new GrayM with the given bounds and maximum channel
// value.
func NewGrayM(r image.Rectangle, m uint8) *GrayM {
w, h := r.Dx(), r.Dy()
pix := make([]uint8, 1*w*h)
model := npcolor.GrayMModel{M: m}
return &GrayM{pix, 1 * w, r, model}
}
// GrayM32 is an in-memory image whose At method returns npcolor.GrayM32 values.
type GrayM32 struct {
// Pix holds the image's pixels, as gray values. The pixel at
// (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*1].
Pix []uint8
// Stride is the Pix stride (in bytes) between vertically adjacent pixels.
Stride int
// Rect is the image's bounds.
Rect image.Rectangle
// Model is the image's color model.
Model npcolor.GrayM32Model
}
// ColorModel returns the GrayM32 image's color model.
func (p *GrayM32) ColorModel() color.Model { return p.Model }
// Bounds returns the domain for which At can return non-zero color. The
// bounds do not necessarily contain the point (0, 0).
func (p *GrayM32) Bounds() image.Rectangle { return p.Rect }
// At returns the color of the pixel at (x, y) as a color.Color.
// At(Bounds().Min.X, Bounds().Min.Y) returns the upper-left pixel of the grid.
// At(Bounds().Max.X-1, Bounds().Max.Y-1) returns the lower-right one.
func (p *GrayM32) At(x, y int) color.Color {
return p.GrayM32At(x, y)
}
// GrayM32At returns the color of the pixel at (x, y) as an npcolor.GrayM32.
func (p *GrayM32) GrayM32At(x, y int) npcolor.GrayM32 {
if !(image.Point{x, y}.In(p.Rect)) {
return npcolor.GrayM32{}
}
i := p.PixOffset(x, y)
return npcolor.GrayM32{
Y: uint16(p.Pix[i+0])<<8 | uint16(p.Pix[i+1]),
M: p.Model.M,
}
}
// PixOffset returns the index of the first element of Pix that corresponds to
// the pixel at (x, y).
func (p *GrayM32) PixOffset(x, y int) int {
return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*2
}
// Set sets the pixel at (x, y) to a given color, expressed as a color.Color.
func (p *GrayM32) Set(x, y int, c color.Color) {
if !(image.Point{x, y}.In(p.Rect)) {
return
}
i := p.PixOffset(x, y)
c1 := p.Model.Convert(c).(npcolor.GrayM32)
p.Pix[i+0] = uint8(c1.Y >> 8)
p.Pix[i+1] = uint8(c1.Y)
}
// SetGrayM32 sets the pixel at (x, y) to a given color, expressed as an
// npcolor.GrayM32.
func (p *GrayM32) SetGrayM32(x, y int, c npcolor.GrayM32) {
if !(image.Point{x, y}.In(p.Rect)) {
return
}
i := p.PixOffset(x, y)
if c.M == p.Model.M {
p.Pix[i+0] = uint8(c.Y >> 8)
p.Pix[i+1] = uint8(c.Y)
} else {
p.Set(x, y, c)
}
}
// SubImage returns an image representing the portion of the image p visible
// through r. The returned value shares pixels with the original image.
func (p *GrayM32) SubImage(r image.Rectangle) image.Image {
r = r.Intersect(p.Rect)
// If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to
// be inside either r1 or r2 if the intersection is empty. Without
// explicitly checking for this, the Pix[i:] expression below can
// panic.
if r.Empty() {
return &GrayM32{}
}
i := p.PixOffset(r.Min.X, r.Min.Y)
return &GrayM32{
Pix: p.Pix[i:],
Stride: p.Stride,
Rect: r,
}
}
// Opaque scans the entire image and reports whether it is fully opaque.
func (p *GrayM32) Opaque() bool {
return true
}
// MaxValue returns the maximum grayscale value allowed.
func (p *GrayM32) MaxValue() uint16 {
return uint16(p.Model.M)
}
// Format identifies the image as a PGM image.
func (p *GrayM32) Format() Format {
return PGM
}
// HasAlpha indicates that there is no alpha channel.
func (p *GrayM32) HasAlpha() bool {
return false
}
// PromoteToRGBM64 generates a 16-bit color image that looks identical to
// the given grayscale image.
func (p *GrayM32) PromoteToRGBM64() *RGBM64 {
rgb := NewRGBM64(p.Bounds(), p.Model.M)
for i, g := range p.Pix {
base := i / 2
ofs := i % 2
rgb.Pix[base*6+ofs+0] = g
rgb.Pix[base*6+ofs+2] = g
rgb.Pix[base*6+ofs+4] = g
}
return rgb
}
// NewGrayM32 returns a new GrayM32 with the given bounds and maximum channel
// value.
func NewGrayM32(r image.Rectangle, m uint16) *GrayM32 {
w, h := r.Dx(), r.Dy()
pix := make([]uint8, 2*w*h)
model := npcolor.GrayM32Model{M: m}
return &GrayM32{pix, 2 * w, r, model}
}
// decodeConfigPGMWithComments reads and parses a PGM header, either "raw"
// (binary) or "plain" (ASCII). Unlike decodeConfigPGM, it also returns any
// comments appearing in the file.
func decodeConfigPGMWithComments(r io.Reader) (image.Config, []string, error) {
// We really want a bufio.Reader. If we were given one, use it. If
// not, create a new one.
br, ok := r.(*bufio.Reader)
if !ok {
br = bufio.NewReader(r)
}
nr := newNetpbmReader(br)
// Parse the PGM header.
header, ok := nr.GetNetpbmHeader()
if !ok {
err := nr.Err()
if err == nil {
err = errors.New("Invalid PGM header")
}
return image.Config{}, nil, err
}
// Store and return the image configuration.
var cfg image.Config
cfg.Width = header.Width
cfg.Height = header.Height
if header.Maxval < 256 {
cfg.ColorModel = npcolor.GrayMModel{M: uint8(header.Maxval)}
} else {
cfg.ColorModel = npcolor.GrayM32Model{M: uint16(header.Maxval)}
}
return cfg, header.Comments, nil
}
// decodeConfigPGM reads and parses a PGM header, either "raw"
// (binary) or "plain" (ASCII).
func decodeConfigPGM(r io.Reader) (image.Config, error) {
img, _, err := decodeConfigPGMWithComments(r)
return img, err
}
// decodePGMWithComments reads a complete "raw" (binary) PGM image. Unlike
// decodePGM, it also returns any comments appearing in the file.
func decodePGMWithComments(r io.Reader) (image.Image, []string, error) {
// Read the image header, and use it to prepare a grayscale image.
br := bufio.NewReader(r)
config, comments, err := decodeConfigPGMWithComments(br)
if err != nil {
return nil, nil, err
}
// Create either a Gray or a Gray16 image.
var img image.Image // Image to return
var data []uint8 // Image data
var maxVal uint // 100% white value
switch model := config.ColorModel.(type) {
case npcolor.GrayMModel:
maxVal = uint(model.M)
gray := NewGrayM(image.Rect(0, 0, config.Width, config.Height), uint8(maxVal))
data = gray.Pix
img = gray
case npcolor.GrayM32Model:
maxVal = uint(model.M)
gray := NewGrayM32(image.Rect(0, 0, config.Width, config.Height), uint16(maxVal))
data = gray.Pix
img = gray
default:
panic("Unexpected color model")
}
// Raw PGM images are nice because we can read directly into the image
// data.
for len(data) > 0 {
nRead, err := br.Read(data)
if err != nil && err != io.EOF {
return img, nil, err
}
if nRead == 0 {
return img, nil, errors.New("Failed to read binary PGM data")
}
data = data[nRead:]
}
return img, comments, nil
}
// decodePGM reads a complete "raw" (binary) PGM image.
func decodePGM(r io.Reader) (image.Image, error) {
img, _, err := decodePGMWithComments(r)
return img, err
}
// decodePGMPlainWithComments reads a complete "plain" (ASCII) PGM image.
// Unlike decodePGMPlain, it also returns any comments appearing in the file.
func decodePGMPlainWithComments(r io.Reader) (image.Image, []string, error) {
// Read the image header, and use it to prepare a grayscale image.
br := bufio.NewReader(r)
config, comments, err := decodeConfigPGMWithComments(br)
if err != nil {
return nil, nil, err
}
var img image.Image // Image to return
// Define a simple error handler.
nr := newNetpbmReader(br)
badness := func() (image.Image, []string, error) {
// Something went wrong. Either we have an error code to
// explain what or we make up a generic error message.
err := nr.Err()
if err == nil {
err = errors.New("Failed to parse ASCII PGM data")
}
return img, nil, err
}
// Create either a Gray or a Gray16 image.
var data []uint8 // Image data
var maxVal int // 100% white value
switch model := config.ColorModel.(type) {
case npcolor.GrayMModel:
maxVal = int(model.M)
gray := NewGrayM(image.Rect(0, 0, config.Width, config.Height), uint8(maxVal))
data = gray.Pix
img = gray
case npcolor.GrayM32Model:
maxVal = int(model.M)
gray := NewGrayM32(image.Rect(0, 0, config.Width, config.Height), uint16(maxVal))
data = gray.Pix
img = gray
default:
panic("Unexpected color model")
}
// Read ASCII base-10 integers into the image data.
if !nr.GetASCIIData(maxVal, data) {
return badness()
}
return img, comments, nil
}
// decodePGMPlain reads a complete "plain" (ASCII) PGM image.
func decodePGMPlain(r io.Reader) (image.Image, error) {
img, _, err := decodePGMPlainWithComments(r)
return img, err
}
// Indicate that we can decode both raw and plain PGM files.
func init() {
image.RegisterFormat("pgm", "P5", decodePGM, decodeConfigPGM)
image.RegisterFormat("pgm", "P2", decodePGMPlain, decodeConfigPGM)
}
// encodePGM writes an arbitrary image in PGM format.
func encodePGM(w io.Writer, img image.Image, opts *EncodeOptions) error {
// Write the PGM header.
if opts.Plain {
fmt.Fprintln(w, "P2")
} else {
fmt.Fprintln(w, "P5")
}
for _, cmt := range opts.Comments {
cmt = strings.Replace(cmt, "\n", " ", -1)
cmt = strings.Replace(cmt, "\r", " ", -1)
fmt.Fprintf(w, "# %s\n", cmt)
}
rect := img.Bounds()
width := rect.Max.X - rect.Min.X
height := rect.Max.Y - rect.Min.Y
fmt.Fprintf(w, "%d %d\n", width, height)
fmt.Fprintf(w, "%d\n", opts.MaxValue)
// Write the PGM data.
if opts.MaxValue < 256 {
return encodeGrayData(w, img, opts)
}
return encodeGray32Data(w, img, opts)
}
// encodeGrayData writes image data as 8-bit samples.
func encodeGrayData(w io.Writer, img image.Image, opts *EncodeOptions) error {
// In the background, write each 8-bit color sample into a channel.
rect := img.Bounds()
width := rect.Max.X - rect.Min.X
samples := make(chan uint16, width)
go func() {
cm := npcolor.GrayMModel{M: uint8(opts.MaxValue)}
for y := rect.Min.Y; y < rect.Max.Y; y++ {
for x := rect.Min.X; x < rect.Max.X; x++ {
c := cm.Convert(img.At(x, y)).(npcolor.GrayM)
samples <- uint16(c.Y)
}
}
close(samples)
}()
// In the foreground, consume grayscale samples and write them to the
// image file.
if opts.Plain {
return writePlainData(w, samples)
}
return writeRawData(w, samples, 1)
}
// encodeGray32Data writes image data as 16-bit samples.
func encodeGray32Data(w io.Writer, img image.Image, opts *EncodeOptions) error {
// In the background, write each 16-bit color sample into a channel.
rect := img.Bounds()
width := rect.Max.X - rect.Min.X
samples := make(chan uint16, width)
go func() {
cm := npcolor.GrayM32Model{M: opts.MaxValue}
for y := rect.Min.Y; y < rect.Max.Y; y++ {
for x := rect.Min.X; x < rect.Max.X; x++ {
c := cm.Convert(img.At(x, y)).(npcolor.GrayM32)
samples <- c.Y
}
}
close(samples)
}()
// In the foreground, consume grayscale samples and write them to the
// image file.
if opts.Plain {
return writePlainData(w, samples)
}
return writeRawData(w, samples, 2)
}