-
Notifications
You must be signed in to change notification settings - Fork 629
/
Copy pathPyOpenEXR.cpp
2755 lines (2400 loc) · 85.8 KB
/
PyOpenEXR.cpp
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) Contributors to the OpenEXR Project.
//
//#define DEBUG_VERBOSE 1
#define PYBIND11_DETAILED_ERROR_MESSAGES 1
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
#include <pybind11/eval.h>
#include <pybind11/pytypes.h>
#include <pybind11/stl_bind.h>
#include <pybind11/operators.h>
#include "openexr.h"
#include <ImfHeader.h>
#include <ImfMultiPartInputFile.h>
#include <ImfMultiPartOutputFile.h>
#include <ImfInputPart.h>
#include <ImfOutputPart.h>
#include <ImfTiledOutputPart.h>
#include <ImfDeepScanLineOutputPart.h>
#include <ImfDeepScanLineInputPart.h>
#include <ImfDeepTiledOutputPart.h>
#include <ImfDeepTiledInputPart.h>
#include <ImfDeepFrameBuffer.h>
#include <ImfPartType.h>
#include <ImfArray.h>
#include <ImfBoxAttribute.h>
#include <ImfChannelListAttribute.h>
#include <ImfChromaticitiesAttribute.h>
#include <ImfCompressionAttribute.h>
#include <ImfDoubleAttribute.h>
#include <ImfEnvmapAttribute.h>
#include <ImfFloatAttribute.h>
#include <ImfIntAttribute.h>
#include <ImfKeyCodeAttribute.h>
#include <ImfLineOrderAttribute.h>
#include <ImfMatrixAttribute.h>
#include <ImfPreviewImageAttribute.h>
#include <ImfRationalAttribute.h>
#include <ImfStringAttribute.h>
#include <ImfStringVectorAttribute.h>
#include <ImfFloatVectorAttribute.h>
#include <ImfTileDescriptionAttribute.h>
#include <ImfTimeCodeAttribute.h>
#include <ImfVecAttribute.h>
#include <typeinfo>
#include <sys/types.h>
namespace py = pybind11;
using namespace py::literals;
using namespace OPENEXR_IMF_NAMESPACE;
using namespace IMATH_NAMESPACE;
extern bool init_OpenEXR_old(PyObject* module);
namespace pybind11 {
namespace detail {
// From https://github.com/AcademySoftwareFoundation/OpenImageIO/blob/master/src/python/py_oiio.h
//
// This half casting support for numpy was all derived from discussions
// here: https://github.com/pybind/pybind11/issues/1776
// Similar to enums in `pybind11/numpy.h`. Determined by doing:
// python3 -c 'import numpy as np; print(np.dtype(np.float16).num)'
constexpr int NPY_FLOAT16 = 23;
template<> struct npy_format_descriptor<half> {
static pybind11::dtype dtype()
{
handle ptr = npy_api::get().PyArray_DescrFromType_(NPY_FLOAT16);
return reinterpret_borrow<pybind11::dtype>(ptr);
}
static std::string format()
{
// following: https://docs.python.org/3/library/struct.html#format-characters
return "e";
}
static constexpr auto name = _("float16");
};
} // namespace detail
} // namespace pybind11
namespace {
#include "PyOpenEXR.h"
//
// Create a PyFile out of a list of parts (i.e. a multi-part file)
//
PyFile::PyFile(const py::list& parts)
: parts(parts)
{
int part_index = 0;
for (auto p : this->parts)
{
if (!py::isinstance<PyPart>(p))
throw std::invalid_argument("must be a list of OpenEXR.Part() objects");
PyPart& P = p.cast<PyPart&>();
P.part_index = part_index++;
}
}
//
// Create a PyFile out of a single part: header, channels,
// type, and compression (i.e. a single-part file)
//
PyFile::PyFile(const py::dict& header, const py::dict& channels)
{
parts.append(py::cast<PyPart>(PyPart(header, channels, "")));
}
//
// Read a PyFile from the given filename.
//
// Create a 'Part' for each part in the file, even single-part files. The API
// has convenience methods for accessing the first part's header and
// channels, which for single-part files appears as the file's data.
//
// By default, read each channel into a numpy array of the appropriate pixel
// type: uint32, half, or float.
//
// If 'separate_channels' is false, gather 'R', 'G', 'B', and 'A' channels and interleave
// them into a 3- or 4- (if 'A' is present) element numpy array. In the case
// of raw 'R', 'G', 'B', and 'A' channels, the corresponding key in the
// channels dict is "RGB" or "RGBA". For channels with a prefix,
// e.g. "left.R", "left.G", etc, the channel key is the prefix.
//
PyFile::PyFile(const std::string& filename, bool separate_channels, bool header_only)
: filename(filename), header_only(header_only)
{
MultiPartInputFile infile(filename.c_str());
for (int part_index = 0; part_index < infile.parts(); part_index++)
{
const Header& header = infile.header(part_index);
PyPart P;
P.part_index = part_index;
const Box2i& dw = header.dataWindow();
auto width = static_cast<size_t>(dw.max.x - dw.min.x + 1);
auto height = static_cast<size_t>(dw.max.y - dw.min.y + 1);
//
// Fill the header dict with attributes from the input file header
//
for (auto a = header.begin(); a != header.end(); a++)
{
std::string name = a.name();
const Attribute& attribute = a.attribute();
P.header[py::str(name)] = getAttributeObject(name, &attribute);
}
//
// If we're only reading the header, we're done.
//
if (header_only)
continue;
//
// If we're gathering RGB channels, identify which channels to gather
// by examining common prefixes.
//
std::set<std::string> rgbaChannels;
if (!separate_channels)
{
for (auto c = header.channels().begin(); c != header.channels().end(); c++)
{
std::string py_channel_name;
char channel_name;
if (P.channelNameToRGBA(header.channels(), c.name(), py_channel_name, channel_name) > 0)
rgbaChannels.insert(c.name());
}
}
std::vector<size_t> shape ({height, width});
//
// Read the channel data, different for image vs. deep
//
auto type = header.type();
if (type == SCANLINEIMAGE || type == TILEDIMAGE)
{
P.readPixels(infile, header.channels(), shape, rgbaChannels, dw, separate_channels);
}
else if (type == DEEPSCANLINE || type == DEEPTILE)
{
P.readDeepPixels(infile, type, header.channels(), shape, rgbaChannels, dw, separate_channels);
}
parts.append(py::cast<PyPart>(PyPart(P)));
} // for parts
}
void
PyPart::readPixels(MultiPartInputFile& infile, const ChannelList& channel_list,
const std::vector<size_t>& shape, const std::set<std::string>& rgbaChannels,
const Box2i& dw, bool separate_channels)
{
FrameBuffer frameBuffer;
for (auto c = channel_list.begin(); c != channel_list.end(); c++)
{
std::string py_channel_name = c.name();
char channel_name;
int nrgba = 0;
if (!separate_channels)
nrgba = channelNameToRGBA(channel_list, c.name(), py_channel_name, channel_name);
auto py_channel_name_str = py::str(py_channel_name);
if (!channels.contains(py_channel_name_str))
{
//
// We haven't add a PyChannel yet, so add one now.
//
PyChannel C;
C.name = py_channel_name;
C.xSampling = c.channel().xSampling;
C.ySampling = c.channel().ySampling;
C.pLinear = c.channel().pLinear;
const auto style = py::array::c_style | py::array::forcecast;
std::vector<size_t> c_shape = shape;
//
// If this channel belongs to one of the rgba's, give
// the PyChannel the extra dimension and the proper shape.
// nrgba is 3 for RGB and 4 for RGBA.
//
if (rgbaChannels.find(c.name()) != rgbaChannels.end())
c_shape.push_back(nrgba);
switch (c.channel().type)
{
case UINT:
C.pixels = py::array_t<uint32_t,style>(c_shape);
break;
case HALF:
C.pixels = py::array_t<half,style>(c_shape);
break;
case FLOAT:
C.pixels = py::array_t<float,style>(c_shape);
break;
default:
throw std::runtime_error("invalid pixel type");
} // switch c->type
channels[py_channel_name.c_str()] = C;
}
//
// Add a slice to the framebuffer
//
auto v = channels[py_channel_name.c_str()];
auto C = v.cast<PyChannel&>();
py::buffer_info buf = C.pixels.request();
auto basePtr = static_cast<uint8_t*>(buf.ptr);
//
// Offset the pointer for the channel
//
py::dtype dt = C.pixels.dtype();
size_t xStride = dt.itemsize();
if (nrgba > 0)
{
xStride *= nrgba;
switch (channel_name)
{
case 'R':
break;
case 'G':
basePtr += dt.itemsize();
break;
case 'B':
basePtr += 2 * dt.itemsize();
break;
case 'A':
basePtr += 3 * dt.itemsize();
break;
default:
break;
}
}
size_t yStride = xStride * shape[1] / C.xSampling;
frameBuffer.insert (c.name(),
Slice::Make (c.channel().type,
(void*) basePtr,
dw, xStride, yStride,
C.xSampling,
C.ySampling));
} // for header.channels()
//
// Read the pixels
//
InputPart part (infile, part_index);
part.setFrameBuffer (frameBuffer);
part.readPixels (dw.min.y, dw.max.y);
}
void
PyChannel::createDeepPixelArrays(size_t height, size_t width, const Array2D<unsigned int>& sampleCount)
{
//
// Create the py::array of the appropriate type and shape to hold the
// samples for each pixel
//
std::vector<size_t> shape;
shape.push_back(0);
if (_nrgba > 0)
shape.push_back(_nrgba); // shape=(count,3) for RGB; shape=(count,4) for RGBA
py::object* pixel_objects = static_cast<py::object*>(pixels.mutable_data());
for (size_t y=0; y<height; y++)
for (size_t x=0; x<width; x++)
{
auto i = y * width + x;
if (sampleCount[y][x] == 0)
{
//
// No samples, no array.
//
pixel_objects[i] = py::none();
}
else
{
shape[0] = sampleCount[y][x];
switch (_type)
{
case UINT:
pixel_objects[i] = py::array_t<uint32_t>(shape);
break;
case HALF:
pixel_objects[i] = py::array_t<half>(shape);
break;
case FLOAT:
pixel_objects[i] = py::array_t<float>(shape);
break;
default:
throw std::runtime_error("invalid pixel type");
} // switch _type
}
}
}
void
PyPart::setDeepSliceData(const ChannelList& channel_list, size_t height, size_t width,
SliceDataMap& sliceDataMap,
std::map<std::string,PyChannel*>& rgbaChannelMap,
const Array2D<unsigned int>& sampleCount)
{
//
// Now that we know the sample counts, create the sample array for
// each pixel. For RGB images, the sample arrays are of shape
// (count, 3), or (count,4) if there's an A channel. For separate
// channels, the arrays are 1D. The arrays are None for pixels with
// no samples.
//
for (auto c : channels)
{
auto C = py::cast<PyChannel&>(c.second);
C.createDeepPixelArrays(height, width, sampleCount);
}
for (auto c = channel_list.begin(); c != channel_list.end(); c++)
{
//
// Set the slice data pointers to point into the pixel sample
// arrays, with the proper offset/stride when coalescing channels
// into RGB/RGBA.
//
auto &sliceData = *sliceDataMap[c.name()];
PyChannel& C = *rgbaChannelMap[c.name()];
py::object* pixel_objects = static_cast<py::object*>(C.pixels.mutable_data());
size_t channel_offset = 0;
if (C._nrgba > 0)
{
if (!strcmp(c.name(), "G"))
channel_offset = 1;
else if (!strcmp(c.name(), "B"))
channel_offset = 2;
else if (!strcmp(c.name(), "A"))
channel_offset = 3;
}
for (size_t y=0; y<height; y++)
for (size_t x=0; x<width; x++)
if (sampleCount[y][x] == 0)
sliceData[y][x] = nullptr;
else
{
auto i = y * width + x;
auto a = py::cast<py::array>(pixel_objects[i]);
switch (C._type)
{
case UINT:
{
auto d = static_cast<uint32_t*>(a.request().ptr);
sliceData[y][x] = static_cast<void*>(&d[channel_offset]);
}
break;
case HALF:
{
auto d = static_cast<half*>(a.request().ptr);
sliceData[y][x] = static_cast<void*>(&d[channel_offset]);
}
break;
case FLOAT:
{
auto d = static_cast<float*>(a.request().ptr);
sliceData[y][x] = static_cast<void*>(&d[channel_offset]);
}
break;
case NUM_PIXELTYPES:
break;
}
}
}
}
void
PyPart::readDeepPixels(MultiPartInputFile& infile, const std::string& type, const ChannelList& channel_list,
const std::vector<size_t>& shape, const std::set<std::string>& rgbaChannels,
const Box2i& dw, bool separate_channels)
{
size_t width = dw.max.x - dw.min.x + 1;
size_t height = dw.max.y - dw.min.y + 1;
auto dw_offset = dw.min.y * width + dw.min.x;
Array2D<unsigned int> sampleCount (height, width);
DeepFrameBuffer frameBuffer;
frameBuffer.insertSampleCountSlice (Slice (UINT,
(char*) (&sampleCount[0][0] - dw_offset),
sizeof (unsigned int) * 1, // xStride
sizeof (unsigned int) * width)); // yStride
//
// Map from channel name to 2D array of pointers to sample arrays for
// each slice.
SliceDataMap sliceDataMap;
//
// The channel_list argument is the Imf::Header's list of channels.
//
// When building a py::dict of channels that coalesces "R", "G", "B", and
// 'A' channels into "RGBA", the PyPart's channels py::dict has a single
// entry for all 4 (or 3 if no alpha). rgbaChannelMap maps the
// channel_list names (e.g. "R") to the PyChannel name (e.g. "RGBA").
//
//
std::map<std::string,PyChannel*> rgbaChannelMap;
for (auto c = channel_list.begin(); c != channel_list.end(); c++)
{
std::string py_channel_name = c.name();
char channel_name;
int nrgba = 0;
if (!separate_channels)
nrgba = channelNameToRGBA(channel_list, c.name(), py_channel_name, channel_name);
auto py_channel_name_str = py::str(py_channel_name);
if (!channels.contains(py_channel_name_str))
{
// We haven't add a PyChannel yet, so add one now.
channels[py_channel_name.c_str()] = PyChannel();
PyChannel& C = channels[py_channel_name.c_str()].cast<PyChannel&>();
C.name = py_channel_name;
C.xSampling = c.channel().xSampling;
C.ySampling = c.channel().ySampling;
C.pLinear = c.channel().pLinear;
C.pixels = py::array(py::dtype("O"), {height,width});
C._type = c.channel().type;
C._nrgba = nrgba;
}
auto v = channels[py_channel_name.c_str()];
rgbaChannelMap[c.name()] = v.cast<PyChannel*>();
size_t xStride = sizeof(void*);
size_t yStride = xStride * shape[1];
size_t sampleStride;
switch (c.channel().type)
{
case UINT:
sampleStride = sizeof(uint32_t);
break;
case HALF:
sampleStride = sizeof(half);
break;
case FLOAT:
sampleStride = sizeof(float);
break;
default:
sampleStride = 0;
break;
}
//
// If coalescing RGBA, the sampleStride strides all of RGBA.
//
if (nrgba > 0)
sampleStride *= nrgba;
sliceDataMap[c.name()] = std::unique_ptr<Array2DVoidPtr>(new Array2DVoidPtr(height, width));
Array2DVoidPtr* sliceData = sliceDataMap[c.name()].get();
auto base = &(*sliceData)[0][0] - dw_offset;
frameBuffer.insert (c.name(),
DeepSlice (c.channel().type,
(char*) base,
xStride,
yStride,
sampleStride,
c.channel().xSampling,
c.channel().ySampling));
} // for header.channels()
if (type == DEEPSCANLINE)
{
DeepScanLineInputPart part (infile, part_index);
part.setFrameBuffer (frameBuffer);
part.readPixelSampleCounts (dw.min.y, dw.max.y);
setDeepSliceData(channel_list, height, width, sliceDataMap, rgbaChannelMap, sampleCount);
part.readPixels (dw.min.y, dw.max.y);
}
else if (type == DEEPTILE)
{
DeepTiledInputPart part (infile, part_index);
part.setFrameBuffer (frameBuffer);
int numXTiles = part.numXTiles (0);
int numYTiles = part.numYTiles (0);
part.readPixelSampleCounts (0, numXTiles - 1, 0, numYTiles - 1);
setDeepSliceData(channel_list, height, width, sliceDataMap, rgbaChannelMap, sampleCount);
part.readTiles (0, numXTiles - 1, 0, numYTiles - 1);
}
}
void
PyPart::writePixels(MultiPartOutputFile& outfile, const Box2i& dw) const
{
FrameBuffer frameBuffer;
for (auto c : channels)
{
auto C = c.second.cast<const PyChannel&>();
auto pixelType = C.pixelType();
if (C.pixels.ndim() == 3)
{
//
// The py::dict has RGB or RGBA channels, but the
// framebuffer needs a slice per dimension
//
std::string name_prefix;
if (C.name == "RGB" || C.name == "RGBA")
name_prefix = "";
else
name_prefix = C.name + ".";
py::buffer_info buf = C.pixels.request();
auto basePtr = static_cast<uint8_t*>(buf.ptr);
py::dtype dt = C.pixels.dtype();
int nrgba = C.pixels.shape(2);
size_t xStride = dt.itemsize() * nrgba;
size_t yStride = xStride * width() / C.xSampling;
auto rPtr = basePtr;
frameBuffer.insert (name_prefix + "R",
Slice::Make (pixelType,
static_cast<void*>(rPtr),
dw, xStride, yStride,
C.xSampling,
C.ySampling));
auto gPtr = &basePtr[dt.itemsize()];
frameBuffer.insert (name_prefix + "G",
Slice::Make (pixelType,
static_cast<void*>(gPtr),
dw, xStride, yStride,
C.xSampling,
C.ySampling));
auto bPtr = &basePtr[2*dt.itemsize()];
frameBuffer.insert (name_prefix + "B",
Slice::Make (pixelType,
static_cast<void*>(bPtr),
dw, xStride, yStride,
C.xSampling,
C.ySampling));
if (nrgba == 4)
{
auto aPtr = &basePtr[3*dt.itemsize()];
frameBuffer.insert (name_prefix + "A",
Slice::Make (pixelType,
static_cast<void*>(aPtr),
dw, xStride, yStride,
C.xSampling,
C.ySampling));
}
}
else
{
frameBuffer.insert (C.name,
Slice::Make (pixelType,
static_cast<void*>(C.pixels.request().ptr),
dw, 0, 0,
C.xSampling,
C.ySampling));
}
}
if (type() == EXR_STORAGE_SCANLINE)
{
OutputPart part(outfile, part_index);
part.setFrameBuffer (frameBuffer);
part.writePixels (height());
}
else
{
TiledOutputPart part(outfile, part_index);
part.setFrameBuffer (frameBuffer);
part.writeTiles (0, part.numXTiles() - 1, 0, part.numYTiles() - 1);
}
}
template<class T>
void
PyChannel::setSliceDataPtr(Array2DVoidPtr& sliceData,const py::array& a, size_t y, size_t x,
int channel_offset, PixelType type) const
{
auto s = py::cast<const py::array_t<T>>(a);
auto d = static_cast<const T*>(s.request().ptr);
const void* v = static_cast<const void*>(&d[channel_offset]);
sliceData[y][x] = const_cast<void*>(v);
if (_type == NUM_PIXELTYPES)
_type = type;
else if (_type != type)
{
std::stringstream err;
err << "invalid deep pixel array at " << y << "," << x
<< ": all pixels must have same type of samples";
throw std::invalid_argument(err.str());
}
}
int
get_deep_nrgba(const py::array& pixels)
{
const py::object* pixel_objects = static_cast<const py::object*>(pixels.data());
size_t height = pixels.shape(0);
size_t width = pixels.shape(1);
for (size_t y = 0; y<height; y++)
for (size_t x = 0; x<width; x++)
{
auto i = y * width + x;
if (py::isinstance<py::array>(pixel_objects[i]))
{
auto a = py::cast<const py::array>(pixel_objects[i]);
if (a.ndim() == 2)
return a.shape(1);
return 0;
}
}
return 0;
}
void
PyChannel::insertDeepSlice(DeepFrameBuffer& frameBuffer, const std::string& slice_name,
size_t height, size_t width, int nrgba, int dw_offset, int channel_offset,
Array2D<unsigned int>& sampleCount,
std::vector<std::shared_ptr<Array2DVoidPtr>>& sliceDatas) const
{
Array2DVoidPtr* sliceDataPtr = new Array2DVoidPtr(height, width);
Array2DVoidPtr& sliceData(*sliceDataPtr);
sliceDatas.push_back(std::shared_ptr<Array2DVoidPtr>(sliceDataPtr));
auto pixel_objects = static_cast<const py::object*>(pixels.data());
for (size_t y=0; y<height; y++)
for (size_t x=0; x<width; x++)
{
int i = y * width + x;
auto object = pixel_objects[i];
if (object.is(py::none()))
continue;
if (py::isinstance<py::array>(object))
{
auto a = object.cast<py::array>();
if (sampleCount[y][x] == 0)
sampleCount[y][x] = a.shape(0);
else if (sampleCount[y][x] != a.shape(0))
{
std::stringstream err;
err << "invalid sample count at pixel " << y << "," << x
<< ": all channels must have the same number of samples";
throw std::invalid_argument(err.str());
}
if (py::isinstance<py::array_t<uint32_t>>(a))
setSliceDataPtr<uint32_t>(sliceData, a, y, x, channel_offset, UINT);
else if (py::isinstance<py::array_t<half>>(a))
setSliceDataPtr<half>(sliceData, a, y, x, channel_offset, HALF);
else if (py::isinstance<py::array_t<float>>(a))
setSliceDataPtr<float>(sliceData, a, y, x, channel_offset, FLOAT);
else
{
std::stringstream err;
err << "invalid deep pixel array at " << y << "," << x
<< ": unrecognized array type";
throw std::invalid_argument(err.str());
}
}
else
{
std::stringstream err;
err << "invalid deep pixel array at " << y << "," << x
<< ": unrecognized object type";
throw std::invalid_argument(err.str());
}
}
size_t xStride = sizeof(void*);
size_t yStride = xStride * width;
size_t sampleStride;
switch (_type)
{
case UINT:
sampleStride = sizeof(uint32_t);
break;
case HALF:
sampleStride = sizeof(half);
break;
case FLOAT:
sampleStride = sizeof(float);
break;
default:
sampleStride = 0;
break;
}
if (nrgba > 0)
sampleStride *= nrgba;
void* base_ptr = &sliceData[0][0] - dw_offset;
frameBuffer.insert (slice_name,
DeepSlice (_type,
static_cast<char*>(base_ptr),
xStride,
yStride,
sampleStride,
xSampling,
ySampling));
}
void
PyPart::writeDeepPixels(MultiPartOutputFile& outfile, const Box2i& dw) const
{
size_t width = dw.max.x - dw.min.x + 1;
size_t height = dw.max.y - dw.min.y + 1;
auto dw_offset = dw.min.y * width + dw.min.x;
DeepFrameBuffer frameBuffer;
Array2D<unsigned int> sampleCount (height, width);
for (size_t y=0; y<height; y++)
for (size_t x=0; x<width; x++)
sampleCount[y][x] = 0;
frameBuffer.insertSampleCountSlice (Slice (UINT,
(char*) (&sampleCount[0][0] - dw_offset),
sizeof (unsigned int) * 1, // xStride
sizeof (unsigned int) * width)); // yStride
std::vector<std::shared_ptr<Array2DVoidPtr>> sliceDatas;
for (auto c : channels)
{
const PyChannel& C = c.second.cast<const PyChannel&>();
if (C.pixels.dtype().kind() != 'O')
throw std::runtime_error("Expected deep pixel array with dtype 'O'");
C._type = NUM_PIXELTYPES;
int nrgba = get_deep_nrgba(C.pixels);
if (nrgba == 0)
C.insertDeepSlice(frameBuffer, C.name, height, width, nrgba, dw_offset, 0, sampleCount, sliceDatas);
else
{
std::string name_prefix = "";
if (C.name != "RGB" && C.name != "RGBA")
name_prefix = C.name + ".";
C.insertDeepSlice(frameBuffer, name_prefix+"R", height, width, nrgba, dw_offset, 0, sampleCount, sliceDatas);
C.insertDeepSlice(frameBuffer, name_prefix+"G", height, width, nrgba, dw_offset, 1, sampleCount, sliceDatas);
C.insertDeepSlice(frameBuffer, name_prefix+"B", height, width, nrgba, dw_offset, 2, sampleCount, sliceDatas);
if (nrgba == 4)
C.insertDeepSlice(frameBuffer, name_prefix+"A", height, width, nrgba, dw_offset, 3, sampleCount, sliceDatas);
}
}
if (type() == EXR_STORAGE_DEEP_SCANLINE)
{
DeepScanLineOutputPart part(outfile, part_index);
part.setFrameBuffer (frameBuffer);
part.writePixels (height);
}
else
{
DeepTiledOutputPart part(outfile, part_index);
part.setFrameBuffer (frameBuffer);
for (int y = 0; y < part.numYTiles (0); y++)
for (int x = 0; x < part.numXTiles (0); x++)
part.writeTile (x, y, 0);
}
}
//
// Return whether "name" corresponds to one of the 'R', 'G', 'B', or 'A'
// channels in a "RGBA" tuple of channels. Return 4 if there's an 'A'
// channel, 3 if it's just RGB, and 0 otherwise.
//
// py_channel_name is returned as either the prefix, e.g. "left" for
// "left.R", "left.G", "left.B", or "RGBA" if the channel names are just 'R',
// 'G', and 'B'.
//
// This means:
//
// channels["left"] = np.array((height,width,3))
// or:
// channels["RGB"] = np.array((height,width,3))
//
// channel_name is returned as the single character name of the channel
//
int
PyPart::channelNameToRGBA(const ChannelList& channel_list, const std::string& name,
std::string& py_channel_name, char& channel_name)
{
py_channel_name = name;
channel_name = py_channel_name.back();
if (channel_name == 'R' ||
channel_name == 'G' ||
channel_name == 'B' ||
channel_name == 'A')
{
// It has the right final character. The preceding character is either a
// '.' (in the case of "right.R", or empty (in the case of a channel
// called "R")
//
py_channel_name.pop_back();
if (py_channel_name.empty() || py_channel_name.back() == '.')
{
//
// It matches the pattern, but are the other channels also
// present? It's ony "RGBA" if it has all three of 'R', 'G', and
// 'B'.
//
if (channel_list.findChannel(py_channel_name + "R") &&
channel_list.findChannel(py_channel_name + "G") &&
channel_list.findChannel(py_channel_name + "B"))
{
auto A = py_channel_name + "A";
if (!py_channel_name.empty())
py_channel_name.pop_back();
if (py_channel_name.empty())
{
py_channel_name = "RGB";
if (channel_list.findChannel(A))
py_channel_name += "A";
}
if (channel_list.findChannel(A))
return 4;
return 3;
}
}
py_channel_name = name;
}
return 0;
}
py::object
PyFile::__enter__()
{
return py::cast(this);
}
void
PyFile::__exit__(py::args args)
{
for (auto p : parts)
{
PyPart& P = p.cast<PyPart&>();
P.header.clear();
for (auto c : P.channels)
{
auto C = py::cast<PyChannel&>(c.second);
C.pixels = py::none();
}
P.channels.clear();
}
parts = py::list();
}
void
validate_part_index(int part_index, size_t num_parts)
{
if (part_index < 0)
{
std::stringstream s;
s << "Invalid negative part index '" << part_index << "'";
throw std::invalid_argument(s.str());
}
if (static_cast<size_t>(part_index) >= num_parts)
{
std::stringstream s;
s << "Invalid part index '" << part_index
<< "': file has " << num_parts
<< " part";
if (num_parts != 1)
s << "s";
s << ".";
throw std::invalid_argument(s.str());
}
}
py::dict&
PyFile::header(int part_index)