Debian Codegraph @

gavo/utils/imgtools.py

raw
1 """
2 Some miscellaneous helpers for making images and such.
3
4 As this may turn into a fairly expensive import, this should *not* be imported
5 by utils.__init__. Hence, none of these functions are in gavo.api or
6 gavo.utils.
7 """
8
9 #c Copyright 2008-2025, the GAVO project <[email protected]>
10 #c
11 #c This program is free software, covered by the GNU GPL. See the
12 #c COPYING file in the source distribution.
13
14
15 import io
16
17 from PIL import Image
18 import numpy
19
20 from gavo.utils.dachstypes import (Filename, NDArray)
21
22
23 def _normalizeForImage(pixels: NDArray, gamma: float) -> NDArray:
24 """helps jpegFromNumpyArray and friends.
25 """
26 pixels = numpy.flipud(pixels)
27 pixMax, pixMin = numpy.max(pixels), numpy.min(pixels)
28 pixels = numpy.power((pixels-pixMin)/(pixMax-pixMin), gamma)*255
29 return numpy.asarray(pixels, numpy.uint8)
30
31
32 def jpegFromNumpyArray(pixels: NDArray, gamma: float=0.25) -> bytes:
33 """returns a normalized JPEG for numpy pixels.
34
35 pixels is assumed to come from FITS arrays, which are flipped wrt to
36 jpeg coordinates, which is why we're flipping here.
37
38 The normalized intensities are scaled by v^gamma; we believe the default
39 helps with many astronomical images
40 """
41 f = io.BytesIO()
42 Image.fromarray(_normalizeForImage(pixels, gamma)
43 ).save(f, format="jpeg")
44 return f.getvalue()
45
46
47 def colorJpegFromNumpyArrays(
48 rPix: NDArray, gPix: NDArray, bPix: NDArray, gamma: float=0.25
49 ) -> bytes:
50 """as jpegFromNumpyArray, except a color jpeg is built from red, green,
51 and blue pixels.
52 """
53 pixels = numpy.array([
54 _normalizeForImage(rPix, gamma),
55 _normalizeForImage(gPix, gamma),
56 _normalizeForImage(bPix, gamma)]).transpose(1,2,0)
57
58 f = io.BytesIO()
59 Image.fromarray(pixels, mode="RGB").save(f, format="jpeg")
60 return f.getvalue()
61
62
63 def scaleNumpyArray(arr: NDArray, destSize: int) -> NDArray:
64 """returns the numpy array arr scaled down to approximately destSize.
65 """
66 origWidth, origHeight = arr.shape
67 size = max(origWidth, origHeight)
68 scale = max(1, size//destSize+1)
69 destWidth, destHeight = origWidth//scale, origHeight//scale
70
71 # There's very similar code in fitstools.iterScaledRows
72 # -- it would be nice to refactor things so this can be shared.
73 img = numpy.zeros((destWidth, destHeight), 'float32')
74
75 for rowInd in range(destHeight):
76 wideRow = (numpy.sum(
77 arr[:,rowInd*scale:(rowInd+1)*scale], 1, 'float32'
78 )/scale)[:destWidth*scale]
79 # horizontal scaling via reshaping to a matrix and then summing over
80 # its columns.
81 newRow = numpy.sum(
82 numpy.transpose(wideRow.reshape((destWidth, scale))), 0)/scale
83 img[:,rowInd] = newRow
84
85 return img
86
87
88 def getScaledPNG(srcFile: Filename, newWidth: int) -> bytes:
89 """returns PNG bytes that is a scaled version of an image in srcFile.
90
91 srcFile must correspond to something that PIL can read. Since scaling
92 really sucks for non-RGB images, we unconditionally convert whatever we
93 get to 3-band RGB.
94 """
95 im = Image.open(srcFile).convert("RGB")
96 scale = newWidth/float(im.size[0])
97 scaled = im.resize(
98 (newWidth, int(im.size[1]*scale)),
99 Image.Resampling.LANCZOS)
100 f = io.BytesIO()
101 scaled.save(f, format="png")
102 return f.getvalue()