-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathtest_image.py
More file actions
600 lines (453 loc) · 16.4 KB
/
Copy pathtest_image.py
File metadata and controls
600 lines (453 loc) · 16.4 KB
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
# vim: set fileencoding=utf-8 :
import struct
import sys
import pyvips
import pytest
from helpers import JPEG_FILE, UHDR_FILE, skip_if_no
class TestImage:
def test_pagejoin(self):
image = pyvips.Image.new_from_file(JPEG_FILE)
many_page = image.pagejoin([image, image])
assert many_page.get_page_height() == image.height
assert many_page.height / many_page.get_page_height() == 3
def test_pagesplit(self):
image = pyvips.Image.new_from_file(JPEG_FILE)
many_page = image.pagejoin([image, image])
image_list = many_page.pagesplit()
assert len(image_list) == 3
def test_bandjoin(self):
black = pyvips.Image.black(16, 16)
a = black.draw_rect(1, 0, 0, 1, 1)
b = black.draw_rect(2, 0, 0, 1, 1)
c = black.draw_rect(3, 0, 0, 1, 1)
im = a.bandjoin([b, c, a, b, c, a, b, c])
assert im.width == 16
assert im.height == 16
assert im.bands == 9
x = im.bandjoin([])
assert x.bands == 9
def test_bandslice(self):
black = pyvips.Image.black(16, 16)
a = black.draw_rect(1, 0, 0, 1, 1)
b = black.draw_rect(2, 0, 0, 1, 1)
c = black.draw_rect(3, 0, 0, 1, 1)
d = black.draw_rect(4, 0, 0, 1, 1)
e = black.draw_rect(5, 0, 0, 1, 1)
f = black.draw_rect(6, 0, 0, 1, 1)
im = black.bandjoin([a, b, c, d, e, f])
seq = list(range(im.bands))
x = im[1]
assert x.bands == 1
assert x(0, 0) == [seq[1]]
x = im[1:4]
assert x.bands == 3
assert x(0, 0) == seq[1:4]
x = im[1:4][::-1]
assert x.bands == 3
assert x(0, 0) == seq[1:4][::-1]
x = im[-7]
assert x(0, 0) == [seq[-7]]
x = im[::-1]
assert x(0, 0) == seq[::-1]
x = im[4:6]
assert x(0, 0) == seq[4:6]
x = im[5:3:-1]
assert x(0, 0) == seq[5:3:-1]
x = im[2:4:2]
assert x(0, 0) == seq[2:4:2]
c = im[2:0:-2]
assert x(0, 0) == seq[2:0:-2]
x = im[::-2]
assert x(0, 0) == seq[::-2]
x = im[1::-2]
assert x(0, 0) == seq[1::-2]
x = im[:5:-2]
assert x(0, 0) == seq[:5:-2]
x = im[5:0:-2]
assert x(0, 0) == seq[5:0:-2]
x = im[-10:10]
assert x(0, 0) == seq[-10:10]
indices = [1, 2, 5]
x = im[indices]
assert x(0, 0) == [seq[i] for i in indices]
indices = [1, 2, -7]
x = im[indices]
assert x(0, 0) == [seq[i] for i in indices]
indices = [1]
x = im[indices]
assert x(0, 0) == [seq[1]]
indices = [-1]
x = im[indices]
assert x(0, 0) == [seq[-1]]
boolslice = [True, True, False, False, True, True, False]
x = im[boolslice]
assert x(0, 0) == [seq[i] for i, b in enumerate(boolslice) if b]
with pytest.raises(IndexError):
x = im[4:1]
with pytest.raises(IndexError):
x = im[-(im.bands + 1)]
with pytest.raises(IndexError):
x = im[im.bands]
with pytest.raises(IndexError):
empty = [False] * im.bands
x = im[empty]
with pytest.raises(IndexError):
notenough = [True] * (im.bands - 1)
x = im[notenough]
with pytest.raises(IndexError):
toomany = [True] * (im.bands + 1)
x = im[toomany]
with pytest.raises(IndexError):
empty = []
x = im[empty]
with pytest.raises(IndexError):
oob = [2, 3, -8]
x = im[oob]
with pytest.raises(IndexError):
mixed = [True, 1, True, 2, True, 3, True]
x = im[mixed]
with pytest.raises(IndexError):
wrongtypelist = ['a', 'b', 'c']
x = im[wrongtypelist]
with pytest.raises(IndexError):
wrongargtype = dict(a=1, b=2)
x = im[wrongargtype]
def test_invalidate(self):
try:
import numpy as np
except ImportError:
pytest.skip('numpy not available')
a = np.zeros((1, 1))
p = pyvips.Image.new_from_memory(a.data, 1, 1, 1, 'double')
v = p(0, 0)
assert v == [0]
a[0, 0] = 1
v = p(0, 0)
assert v == [0]
p.invalidate()
v = p(0, 0)
assert v == [1]
def test_to_numpy(self):
try:
import numpy as np
except ImportError:
pytest.skip('numpy not available')
xy = pyvips.Image.xyz(4, 5)
# using __array__ interface:
from pyvips.vimage import TYPESTR_TO_FORMAT
for typestr, format in TYPESTR_TO_FORMAT.items():
this_xy = xy.cast(format)
if typestr == '|b1':
yx = np.asarray(this_xy, dtype=typestr)
else:
yx = np.array(this_xy)
assert yx.dtype == np.dtype(typestr)
assert yx.shape == (5, 4, 2)
assert all(yx.max(axis=(0, 1)) == np.array([3, 4], dtype=typestr))
x, y = xy
x_iy = pyvips.Image.complexform(x, y)
x_iy_dp = x_iy.cast('dpcomplex')
a = np.array(x_iy)
assert a.shape == (5, 4)
assert a.dtype == np.dtype('complex64')
assert a[4, 3].item() == 3+4j
a = np.array(x_iy_dp)
assert a.shape == (5, 4)
assert a.dtype == np.dtype('complex128')
assert a[4, 3].item() == 3+4j
xyxyxy = xy.bandjoin([xy, xy])
a = np.array(xyxyxy)
assert a.shape == (5, 4, 6)
# axes collapsing:
xyxyxy_col = xyxyxy.crop(3, 0, 1, 5)
assert xyxyxy_col.width == 1
assert xyxyxy_col.height == 5
a = np.array(xyxyxy_col)
assert a.shape == (5, 1, 6)
xyxyxy_row = xyxyxy.crop(0, 4, 4, 1)
assert xyxyxy_row.width == 4
assert xyxyxy_row.height == 1
a = np.array(xyxyxy_row)
assert a.shape == (1, 4, 6)
xyxyxy_px = xyxyxy.crop(3, 4, 1, 1)
assert xyxyxy_px.width == 1
assert xyxyxy_px.height == 1
a = np.array(xyxyxy_px)
assert a.shape == (1, 1, 6)
a = np.array(xyxyxy_px[0])
assert a.ndim == 0
# automatic conversion to array on ufunc application:
d = np.diff(xy.cast('short'), axis=1)
assert (d[..., 0] == 1).all()
assert (d[..., 1] == 0).all()
# tests of .numpy() method:
a = pyvips.Image.xyz(256, 1)[0].numpy().squeeze()
assert all(a == np.arange(256))
def test_scipy(self):
try:
import numpy as np
except ImportError:
pytest.skip('numpy not available')
try:
from scipy import ndimage
except ImportError:
pytest.skip('scipy not available')
black = pyvips.Image.black(16, 16)
a = black.draw_rect(1, 0, 0, 1, 1)
d = ndimage.distance_transform_edt(a == 0)
assert np.allclose(d[-1, -1], (2 * 15 ** 2) ** 0.5)
def test_torch(self):
try:
import numpy as np
except ImportError:
pytest.skip('numpy not available')
try:
import torch
except ImportError:
pytest.skip('torch not available')
# torch to Image:
x = torch.outer(torch.arange(10), torch.arange(5))
with pytest.raises(ValueError):
# no vips format for int64
im = pyvips.Image.new_from_array(x)
x = x.float()
im = pyvips.Image.new_from_array(x)
assert im.width == 5
assert im.height == 10
assert im(4, 9) == [36]
assert im.format == 'float'
# Image to torch:
im = pyvips.Image.zone(5, 5)
t = torch.from_numpy(np.asarray(im))
assert t[2, 2] == 1.
def test_from_numpy(self):
try:
import numpy as np
except ImportError:
pytest.skip('numpy not available')
a = np.indices((5, 4)).transpose(1, 2, 0) # (5, 4, 2)
with pytest.raises(ValueError):
# no way in for int64
yx = pyvips.Image.new_from_array(a)
from pyvips.vimage import TYPESTR_TO_FORMAT
for typestr, format in TYPESTR_TO_FORMAT.items():
if typestr == '|b1':
continue
a = np.indices((5, 4), dtype=typestr).transpose(1, 2, 0)
yx = pyvips.Image.new_from_array(a)
assert yx.format == format
a = np.zeros((2, 2, 2, 2))
with pytest.raises(ValueError):
# too many dimensions
im = pyvips.Image.new_from_array(a)
a = np.ones((2, 2, 2), dtype=bool)
im = pyvips.Image.new_from_array(a)
assert im.max() == 255
a = np.ones((2, 2, 2), dtype='S8')
with pytest.raises(ValueError):
# no way in for strings
im = pyvips.Image.new_from_array(a)
# test handling of strided data
a = np.ones((1000, 1000, 3), dtype='uint8')[::10, ::10]
im = pyvips.Image.new_from_array(a)
assert im.width == 100
assert im.height == 100
assert im.bands == 3
class FakeArray(object):
@property
def __array_interface__(self):
return {'shape': (1, 1, 1),
'typestr': '|u1',
'version': 3}
with pytest.raises(TypeError):
# Handle evil objects that don't behave like ndarrays
im = pyvips.Image.new_from_array(FakeArray())
def test_tolist(self):
im = pyvips.Image.complexform(*pyvips.Image.xyz(3, 4))
assert im.tolist()[-1][-1] == 2+3j
im = im.cast('dpcomplex')
assert im.tolist()[-1][-1] == 2+3j
lst = [[1, 2, 3], [4, 5, 6]]
im = pyvips.Image.new_from_array(lst)
assert im.tolist() == lst
assert im.cast('float').tolist() == lst
assert im.cast('complex').tolist() == lst
def test_from_PIL(self):
try:
import PIL.Image
except ImportError:
pytest.skip('PIL not available')
pim = PIL.Image.new('RGB', (42, 23))
im = pyvips.Image.new_from_array(pim)
assert im.format == 'uchar'
assert im.interpretation == 'srgb'
assert im.width == pim.width
assert im.height == pim.height
assert im.min() == 0
assert im.max() == 0
def test_to_PIL_16bit(self):
try:
import PIL.Image
except ImportError:
pytest.skip('PIL not available')
endian = '<' if sys.byteorder == 'little' else '>'
data = struct.pack(
f'{endian}6H',
0x1234,
0x5678,
0x9ABC,
0xDEF0,
0x1111,
0x2222
)
im = pyvips.Image.new_from_memory(data, 2, 1, 3, 'ushort')
try:
import numpy as np
except ImportError:
np = None
if np is not None:
with pytest.raises(TypeError):
PIL.Image.fromarray(im.numpy())
pim = im.pil()
assert pim.mode == 'RGB'
assert pim.size == (2, 1)
assert pim.getpixel((0, 0)) == (0x12, 0x56, 0x9A)
assert pim.getpixel((1, 0)) == (0xDE, 0x11, 0x22)
def test_to_PIL_16bit_rawmode_rgb_rgba(self, monkeypatch):
try:
import PIL.Image as PILImage
except ImportError:
pytest.skip('PIL not available')
seen = []
def fake_frombytes(mode, size, data, decoder_name, rawmode):
seen.append((mode, rawmode))
return PILImage.new(mode, size)
monkeypatch.setattr(PILImage, "frombytes", fake_frombytes)
data = struct.pack('6H', 0x1234, 0x5678, 0x9ABC, 0xDEF0, 0x1111, 0x2222)
im = pyvips.Image.new_from_memory(data, 2, 1, 3, 'ushort')
im.pil()
data = struct.pack('8H', 0x1234, 0x5678, 0x9ABC, 0xDEF0,
0x1111, 0x2222, 0x3333, 0x4444)
im = pyvips.Image.new_from_memory(data, 2, 1, 4, 'ushort')
im.pil()
assert seen[0][0] == 'RGB'
assert seen[1][0] == 'RGBA'
assert seen[0][1] in ('RGB;16L', 'RGB;16B')
assert seen[1][1] in ('RGBA;16L', 'RGBA;16B')
def test_to_PIL_8bit_modes(self):
try:
import PIL.Image
except ImportError:
pytest.skip('PIL not available')
try:
import numpy as np
except ImportError:
pytest.skip('numpy not available')
im = pyvips.Image.new_from_memory(bytes([0, 128, 255, 64]),
2, 2, 1, 'uchar')
pim = im.pil()
assert pim.mode == 'L'
assert pim.size == (2, 2)
assert pim.getpixel((0, 0)) == 0
assert pim.getpixel((1, 0)) == 128
im = pyvips.Image.new_from_memory(bytes([10, 20, 30, 40]),
2, 1, 2, 'uchar')
pim = im.pil()
assert pim.mode == 'LA'
assert pim.getpixel((0, 0)) == (10, 20)
assert pim.getpixel((1, 0)) == (30, 40)
im = pyvips.Image.new_from_memory(bytes([1, 2, 3, 4, 5, 6]),
2, 1, 3, 'uchar')
pim = im.pil()
assert pim.mode == 'RGB'
assert pim.getpixel((0, 0)) == (1, 2, 3)
assert pim.getpixel((1, 0)) == (4, 5, 6)
im = pyvips.Image.new_from_memory(bytes([1, 2, 3, 4, 5, 6, 7, 8]),
2, 1, 4, 'uchar')
pim = im.pil()
assert pim.mode == 'RGBA'
assert pim.getpixel((0, 0)) == (1, 2, 3, 4)
assert pim.getpixel((1, 0)) == (5, 6, 7, 8)
def test_to_PIL_16bit_la(self):
try:
import PIL.Image
except ImportError:
pytest.skip('PIL not available')
endian = '<' if sys.byteorder == 'little' else '>'
data = struct.pack(
f'{endian}4H',
0x1234,
0x5678,
0x9ABC,
0xDEF0
)
im = pyvips.Image.new_from_memory(data, 2, 1, 2, 'ushort')
pim = im.pil()
assert pim.mode == 'RGBA'
assert pim.size == (2, 1)
assert pim.getpixel((0, 0)) == (0x12, 0x12, 0x12, 0x56)
assert pim.getpixel((1, 0)) == (0x9A, 0x9A, 0x9A, 0xDE)
def test_to_PIL_16bit_rgba(self):
try:
import PIL.Image
except ImportError:
pytest.skip('PIL not available')
endian = '<' if sys.byteorder == 'little' else '>'
data = struct.pack(
f'{endian}8H',
0x1234,
0x5678,
0x9ABC,
0xDEF0,
0x1111,
0x2222,
0x3333,
0x4444
)
im = pyvips.Image.new_from_memory(data, 2, 1, 4, 'ushort')
pim = im.pil()
assert pim.mode == 'RGBA'
assert pim.size == (2, 1)
assert pim.getpixel((0, 0)) == (0x12, 0x56, 0x9A, 0xDE)
assert pim.getpixel((1, 0)) == (0x11, 0x22, 0x33, 0x44)
def test_to_PIL_16bit_l(self):
try:
import PIL.Image
except ImportError:
pytest.skip('PIL not available')
try:
import numpy as np
except ImportError:
pytest.skip('numpy not available')
endian = '<' if sys.byteorder == 'little' else '>'
data = struct.pack(f'{endian}2H', 0x1234, 0x9ABC)
im = pyvips.Image.new_from_memory(data, 2, 1, 1, 'ushort')
pim = im.pil()
assert pim.size == (2, 1)
assert pim.getpixel((0, 0)) == 0x1234
assert pim.getpixel((1, 0)) == 0x9ABC
def test_to_PIL_16bit_5band_unsupported(self):
try:
import PIL.Image
except ImportError:
pytest.skip('PIL not available')
data = struct.pack('5H', 0x1111, 0x2222, 0x3333, 0x4444, 0x5555)
im = pyvips.Image.new_from_memory(data, 1, 1, 5, 'ushort')
with pytest.raises(ValueError):
im.pil()
@skip_if_no('uhdrload')
def test_gainmap(self):
def crop_gainmap(image):
gainmap = image.get_gainmap()
if gainmap:
new_gainmap = gainmap.crop(0, 0, 10, 10)
image = image.copy()
image.set_type(pyvips.GValue.image_type,
"gainmap", new_gainmap)
return image
image = pyvips.Image.new_from_file(UHDR_FILE)
image = crop_gainmap(image)
buf = image.write_to_buffer(".jpg")
new_image = pyvips.Image.new_from_buffer(buf, "")
new_gainmap = new_image.get_gainmap()
assert new_gainmap.width == 10