-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgmicpy.cpp
2138 lines (1913 loc) · 84.3 KB
/
gmicpy.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
#include "gmicpy.h"
#include <Python.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "structmember.h"
using namespace std;
//------- G'MIC-PY MACROS ----------//
// Set the GMIC_PY_DEBUG environment variable to any value to enable logging
#ifndef GMIC_PY_LOG
#define GMIC_PY_LOG(msg) \
if (getenv("GMIC_PY_DEBUG")) { \
fprintf(stdout, msg); \
}
#endif
//------- G'MIC MAIN TYPES ----------//
static PyObject *GmicException;
static PyTypeObject PyGmicImageType = {
PyVarObject_HEAD_INIT(NULL, 0) "gmic.GmicImage" /* tp_name */
};
static PyTypeObject PyGmicType = {
PyVarObject_HEAD_INIT(NULL, 0) "gmic.Gmic" /* tp_name */
};
typedef struct {
PyObject_HEAD gmic_image<T> *_gmic_image; // G'MIC library's Gmic Image
} PyGmicImage;
typedef struct {
PyObject_HEAD
// Using a pointer here and PyGmic_new()-time instantiation fixes a
// crash with empty G'MIC command-set.
gmic *_gmic; // G'MIC library's interpreter instance
} PyGmic;
//------- G'MIC INTERPRETER INSTANCE BINDING ----------//
static PyObject *
PyGmic_repr(PyGmic *self)
{
return PyUnicode_FromFormat(
"<%s interpreter object at %p with _gmic address at %p>",
Py_TYPE(self)->tp_name, self, self->_gmic);
}
/* Copy a GmicImage's contents into a gmic_list at a given position. Run this
* typically before a gmic.run(). */
static void
swap_gmic_image_into_gmic_list(PyGmicImage *image, gmic_list<T> &images,
int position)
{
images[position].assign(
image->_gmic_image->_width, image->_gmic_image->_height,
image->_gmic_image->_depth, image->_gmic_image->_spectrum);
images[position]._width = image->_gmic_image->_width;
images[position]._height = image->_gmic_image->_height;
images[position]._depth = image->_gmic_image->_depth;
images[position]._spectrum = image->_gmic_image->_spectrum;
memcpy(images[position]._data, image->_gmic_image->_data,
image->_gmic_image->size() * sizeof(T));
images[position]._is_shared = image->_gmic_image->_is_shared;
}
/* Copy a GmicList's image at given index into an external GmicImage. Run this
* typically after gmic.run(). */
void
swap_gmic_list_item_into_gmic_image(gmic_list<T> &images, int position,
PyGmicImage *image)
{
// Put back the possibly modified reallocated image buffer into the
// original external GmicImage Back up the image data into the original
// external image before it gets freed
swap(image->_gmic_image->_data, images[position]._data);
image->_gmic_image->_width = images[position]._width;
image->_gmic_image->_height = images[position]._height;
image->_gmic_image->_depth = images[position]._depth;
image->_gmic_image->_spectrum = images[position]._spectrum;
image->_gmic_image->_is_shared = images[position]._is_shared;
// Prevent freeing the data buffer's pointer now copied into the external
// image
images[position]._data = 0;
}
#ifdef gmic_py_jupyter_ipython_display
// Cross-platform way to have a temp directory string, through Python
const char *
get_temp_dir()
{
PyObject *module = NULL;
PyObject *pystr = NULL;
module = PyImport_ImportModule("tempfile");
pystr = PyObject_CallMethod(module, "gettempdir", NULL);
Py_XDECREF(pystr);
Py_XDECREF(module);
return PyUnicode_AsUTF8(pystr);
}
// Cross-platform way to have a unique id string, through Python
const char *
get_uuid()
{
PyObject *module = NULL;
PyObject *pystr = NULL;
module = PyImport_ImportModule("uuid");
// Using a time-sortable uuid generator for file names
// See https://stackoverflow.com/a/63970430/420684
pystr = PyObject_Str(PyObject_CallMethod(module, "uuid1", "II", 0, 0));
Py_XDECREF(pystr);
Py_XDECREF(module);
return PyUnicode_AsUTF8(pystr);
}
// You must free the result if result is non-NULL.
// Modified from https://stackoverflow.com/a/779960/420684
// Returns: a tuple of (adapted_gmic_command_string, ["a list of
// fi*le*","glob*","strings*"])
PyObject *
gmic_py_str_replace_display_to_output(char *orig, char *extension)
{
PyObject *pyresult = NULL; // A (result_commands_line, (list,of,filename,
// glob,strings)) 2-elements tuple
PyObject *pyglobs = NULL; // A (result_commands_line, (list,of,filename,
// glob,strings)) 2-elements tuple
char rep[] = " display"; // The string to seek and replace, ie. needle
char replacement_command[] =
" display output "; // The string to seek and replace, ie. needle
char *result; // the return string
char *ins; // the next insert point
char *tmp; // varies
int len_rep; // length of rep (the string to remove)
int len_with; // length of with (the string to replace rep with)
int len_front; // distance between rep and end of last rep
int count; // number of replacements
char with[512]; // replacement path
char with_globbed[512]; // replacement path with glob ending
with[0] = '\0';
with_globbed[0] = '\0';
pyglobs = PyList_New(0);
Py_INCREF(pyglobs);
// sanity checks and initialization
if (!orig || !rep)
return NULL;
len_rep = strlen(rep);
if (len_rep == 0)
return NULL; // empty rep causes infinite loop during count
// build a first uuid to detect fixed replacement string length
// 'with' becomes thus '/tmp/unique-id.png'
// 'with_globbed' becomes '/tmp/unique-id*.png'
strcat(with, replacement_command);
strcat(with, get_temp_dir());
strcat(with, "/");
strcat(with, get_uuid());
strcpy(with_globbed, with);
strcat(with_globbed, "*");
strcat(with, extension);
strcat(with_globbed, extension);
len_with = strlen(with);
// count the number of replacements needed
ins = orig;
for (count = 0; (tmp = strstr(ins, rep)); ++count) {
ins = tmp + len_rep;
}
tmp = result =
(char *)malloc(strlen(orig) + (len_with - len_rep) * count + 1);
if (!result)
return NULL;
// first time through the loop, all the variable are set correctly
// from here on,
// tmp points to the end of the result string
// ins points to the next occurrence of rep in orig
// orig points to the remainder of orig after "end of rep"
while (count--) {
PyList_Append(
pyglobs,
Py_BuildValue("s", with_globbed + strlen(replacement_command)));
ins = strstr(orig, rep);
len_front = ins - orig;
tmp = strncpy(tmp, orig, len_front) + len_front;
tmp = strcpy(tmp, with) + len_with;
orig += len_front + len_rep; // move to next "end of rep"
// recompute a uuid file path for each replacement
with[0] = '\0';
with_globbed[0] = '\0';
strcat(with, replacement_command);
strcat(with, get_temp_dir());
strcat(with, "/");
strcat(with, get_uuid());
strcpy(with_globbed, with);
strcat(with_globbed, "*");
strcat(with, extension);
strcat(with_globbed, extension);
}
strcpy(tmp, orig);
pyresult = PyList_New(0);
PyList_Append(pyresult, Py_BuildValue("s", result));
PyList_Append(pyresult, pyglobs);
Py_DECREF(pyglobs);
return pyresult;
}
PyObject *
gmic_py_display_with_matplotlib_or_ipython(PyObject *image_files_glob_strings)
{
if (!PyList_Check(image_files_glob_strings)) {
PyErr_Format(GmicException, "input globs list is not a Python list");
return NULL;
}
PyObject *ipython_display_module = NULL;
PyObject *matplotlib_pyplot_module = NULL;
PyObject *matplotlib_image_module = NULL;
PyObject *glob_module = NULL;
PyObject *image_glob_str = NULL;
PyObject *image_expanded_filenames = NULL;
PyObject *all_image_expanded_filenames = NULL;
PyObject *image = NULL;
PyObject *display_result = NULL;
unsigned int nb_subplots = 0;
int matplotlib_subplot_id = 1;
bool use_matplotlib = false;
bool use_ipython = false;
unsigned int i = 0;
unsigned int j = 0;
matplotlib_pyplot_module = PyImport_ImportModule("matplotlib.pyplot");
if (matplotlib_pyplot_module == NULL) {
use_matplotlib = false;
ipython_display_module = PyImport_ImportModule("IPython.core.display");
if (ipython_display_module == NULL) {
use_ipython = false;
PyErr_Clear();
PyErr_Format(GmicException,
"Could not use matplotlib neither ipython to try to "
"display images");
return NULL;
}
else {
PyErr_Clear();
use_ipython = true;
}
}
else {
use_matplotlib = true;
use_ipython = false;
matplotlib_image_module = PyImport_ImportModule("matplotlib.image");
}
all_image_expanded_filenames = PyList_New(0);
glob_module = PyImport_ImportModule("glob");
for (i = 0; i < PyList_Size(image_files_glob_strings); i++) {
// display(Image('image_path...', unconfined=True))
image_glob_str = PyList_GetItem(image_files_glob_strings, i);
image_expanded_filenames =
PyObject_CallMethod(glob_module, "glob", "O", image_glob_str);
for (j = 0; j < PyList_Size(image_expanded_filenames); j++) {
PyList_Append(all_image_expanded_filenames,
PyList_GetItem(image_expanded_filenames, j));
}
}
// Sort files by unique ID otherwise they will be in some kind of mess,
// because glob.glob does not sort
PyList_Sort(all_image_expanded_filenames);
nb_subplots = PyList_Size(all_image_expanded_filenames);
for (j = 0; j < nb_subplots; j++) {
if (use_matplotlib) {
image = PyObject_CallMethod(
matplotlib_image_module, "imread", "O",
PyList_GetItem(all_image_expanded_filenames, j));
if (!image) {
return image;
}
display_result =
PyObject_CallMethod(matplotlib_pyplot_module, "subplot", "iii",
nb_subplots, 1, matplotlib_subplot_id++);
if (!display_result) {
return display_result;
}
display_result = PyObject_CallMethod(matplotlib_pyplot_module,
"imshow", "O", image);
if (!display_result) {
return display_result;
}
}
else if (use_ipython) {
image = PyObject_CallMethod(
ipython_display_module, "Image", "O",
PyList_GetItem(all_image_expanded_filenames, j));
if (image == NULL) {
return image;
}
display_result = PyObject_CallMethod(ipython_display_module,
"display", "O", image);
if (display_result == NULL) {
return display_result;
}
}
else {
PyErr_Format(GmicException,
"Logic error: matplotlib or ipython should have "
"been imported at this point.");
return NULL;
}
}
// Matplolib requires only one single image display call, for multiple
// images
if (use_matplotlib) {
display_result =
PyObject_CallMethod(matplotlib_pyplot_module, "show", NULL);
if (!display_result) {
return display_result;
}
Py_XDECREF(all_image_expanded_filenames);
Py_XDECREF(image_expanded_filenames);
Py_XDECREF(image_glob_str);
Py_XDECREF(image);
}
Py_XDECREF(ipython_display_module);
Py_XDECREF(matplotlib_pyplot_module);
Py_XDECREF(glob_module);
return display_result;
}
PyObject *
autoload_wurlitzer_into_ipython()
{
PyObject *wurlitzer_module = NULL;
PyObject *ipython_module = NULL;
PyObject *ipython_handler = NULL;
PyObject *ipython_run_line_magic_result = NULL;
PyObject *ipython_loaded_extensions = NULL;
if (cimg_OS == 1) { // UNIX OSes
wurlitzer_module = PyImport_ImportModule("wurlitzer");
if (wurlitzer_module == NULL) {
PySys_WriteStdout(
"gmic-py: If you do not see any text for G'MIC "
"'print' or "
"'display' commands, you could '!pip install "
"wurlitzer' "
"and if under an IPython environment, run the "
"'%%load_ext "
"wurlitzer' macro. See "
"https://github.com/myselfhimself/gmic-py/issues/"
"64\n");
PyErr_Clear();
}
else { // if wurlitzer module could be imported
ipython_module = PyImport_ImportModule("IPython");
if (ipython_module == NULL) {
PyErr_Clear();
Py_RETURN_NONE;
}
else { // If IPython module found
ipython_handler =
PyObject_CallMethod(ipython_module, "get_ipython", NULL);
if (ipython_handler == NULL) {
PyErr_Clear();
return NULL;
}
// Skip any wurlitzer imported if not in an IPython context, or
// if an IPython terminal
else if (ipython_handler == Py_None ||
!PyObject_HasAttrString(ipython_handler, "kernel")) {
// See
// https://github.com/myselfhimself/gmic-py/issues/63#issuecomment-703533397
Py_XDECREF(ipython_handler);
Py_XDECREF(wurlitzer_module);
Py_XDECREF(ipython_module);
Py_RETURN_NONE;
}
else {
ipython_loaded_extensions = PyObject_GetAttrString(
PyObject_GetAttrString(ipython_handler,
"extension_manager"),
"loaded");
if (ipython_loaded_extensions == NULL) {
PyErr_Clear();
}
else {
// if wurlitzer extension not loaded yet into
// IPython, try to load it
if (PySet_Contains(
ipython_loaded_extensions,
PyUnicode_FromString("wurlitzer")) == 0) {
ipython_run_line_magic_result =
PyObject_CallMethod(ipython_handler,
"run_line_magic", "ss",
"load_ext", "wurlitzer");
if (ipython_run_line_magic_result == NULL) {
PySys_WriteStdout(
"gmic-py: managed to find IPython "
"but "
"could not call the '%%load_ext "
"wurltizer "
"macro for you. If you '!pip "
"install "
"wurlitzer' or install "
"'wurlitzer' in "
"your virtual environment, "
"gmic-py will "
"try to load it for you "
"automatically.\n");
PyErr_Clear();
}
else {
PySys_WriteStderr(
"gmic-py: wurlitzer found (for "
"G'MIC "
"stdout/stderr redirection) and "
"enabled "
"automatically through IPython "
"'%%load_ext wurlitzer'.\n");
}
}
}
}
}
}
}
else { // Non-UNIX OSes
PySys_WriteStdout(
"You are not on a UNIX-like OS and unless you do "
"have a "
"side-window console, you shall not see any text "
"for "
"G'MIC 'print' or 'display' commands output. Hope "
"you can "
"accept it so. See "
"https://github.com/myselfhimself/gmic-py/issues/"
"64\n");
}
Py_XDECREF(wurlitzer_module);
Py_XDECREF(ipython_module);
Py_XDECREF(ipython_handler);
Py_XDECREF(ipython_run_line_magic_result);
return ipython_run_line_magic_result;
}
// end gmic_py_jupyter_ipython_display
#endif
static PyObject *
run_impl(PyObject *self, PyObject *args, PyObject *kwargs)
{
char const *keywords[] = {"command", "images", "image_names", "nodisplay",
NULL};
PyObject *input_gmic_images = NULL;
PyObject *input_gmic_image_names = NULL;
char *commands_line = NULL;
int image_position = 0;
int image_name_position = 0;
int image_names_count = 0;
gmic_list<T> images;
gmic_list<char> image_names; // Empty image names
char *current_image_name_raw = NULL;
PyObject *current_image = NULL;
PyObject *current_image_name = NULL;
PyObject *iter = NULL;
#ifdef gmic_py_jupyter_ipython_display
static bool no_display_checked = false;
static bool no_display_available = false;
PyObject *commands_line_display_to_ouput_result = NULL;
PyObject *ipython_matplotlib_display_result = NULL;
#endif
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|OO", (char **)keywords,
&commands_line, &input_gmic_images,
&input_gmic_image_names)) {
return NULL;
}
try {
Py_XINCREF(input_gmic_images);
Py_XINCREF(input_gmic_image_names);
#ifdef gmic_py_jupyter_ipython_display
// Use a special way of displaying images only if the OS's display
// is not available
if (!no_display_checked) {
no_display_checked = true;
no_display_available = (getenv("DISPLAY") == NULL);
if (no_display_available) {
PySys_WriteStdout("gmic-py: Working in display-less mode.\n");
}
}
if (no_display_available) {
// Provide a fallback for gmic "display" command (without
// supporting arguments) The idea is to replace all
// occurences of "display" by "display output someprefix.png"
commands_line_display_to_ouput_result =
gmic_py_str_replace_display_to_output(commands_line,
(char *)".png");
if (commands_line_display_to_ouput_result == NULL) {
Py_XDECREF(input_gmic_images);
Py_XDECREF(input_gmic_image_names);
// Pass exception upwards
return NULL;
}
commands_line = (char *)PyUnicode_AsUTF8(
PyList_GetItem(commands_line_display_to_ouput_result, 0));
}
#endif
// Grab image names or single image name and check typings
if (input_gmic_image_names != NULL) {
// If list of image names provided
if (PyList_Check(input_gmic_image_names)) {
PyObject *iter = PyObject_GetIter(input_gmic_image_names);
image_names_count = Py_SIZE(input_gmic_image_names);
image_names.assign(image_names_count);
image_name_position = 0;
while ((current_image_name = PyIter_Next(iter))) {
if (!PyUnicode_Check(current_image_name)) {
PyErr_Format(PyExc_TypeError,
"'%.50s' input element found at position "
"%d in "
"'image_names' list is not a '%.400s'",
Py_TYPE(current_image_name)->tp_name,
image_name_position,
PyUnicode_Type.tp_name);
Py_XDECREF(input_gmic_images);
Py_XDECREF(input_gmic_image_names);
return NULL;
}
current_image_name_raw =
(char *)PyUnicode_AsUTF8(current_image_name);
image_names[image_name_position].assign(
strlen(current_image_name_raw) + 1);
memcpy(image_names[image_name_position]._data,
current_image_name_raw,
image_names[image_name_position]._width);
image_name_position++;
}
// If single image name provided
}
else if (PyUnicode_Check(input_gmic_image_names)) {
// Enforce also non-null single-GmicImage 'images'
// parameter
if (input_gmic_images != NULL &&
Py_TYPE(input_gmic_images) !=
(PyTypeObject *)&PyGmicImageType) {
PyErr_Format(PyExc_TypeError,
"'%.50s' 'images' parameter must be a "
"'%.400s' if the "
"'image_names' parameter is a bare '%.400s'.",
Py_TYPE(input_gmic_images)->tp_name,
PyGmicImageType.tp_name,
PyUnicode_Type.tp_name);
Py_XDECREF(input_gmic_images);
Py_XDECREF(input_gmic_image_names);
return NULL;
}
image_names.assign(1);
current_image_name_raw =
(char *)PyUnicode_AsUTF8(input_gmic_image_names);
image_names[0].assign(strlen(current_image_name_raw) + 1);
memcpy(image_names[0]._data, current_image_name_raw,
image_names[0]._width);
// If neither a list of strings nor a single string
// were provided, raise exception
}
else {
PyErr_Format(PyExc_TypeError,
"'%.50s' 'image_names' parameter must be a list "
"of '%.400s'(s)",
Py_TYPE(input_gmic_image_names)->tp_name,
PyUnicode_Type.tp_name);
Py_XDECREF(input_gmic_images);
Py_XDECREF(input_gmic_image_names);
return NULL;
}
}
if (input_gmic_images != NULL) {
// A/ If a list of images was provided
if (PyList_Check(input_gmic_images)) {
image_position = 0;
images.assign(Py_SIZE(input_gmic_images));
// Grab images into a proper gmic_list after checking
// their typing
iter = PyObject_GetIter(input_gmic_images);
while ((current_image = PyIter_Next(iter))) {
// If gmic_list item type is not a GmicImage
if (Py_TYPE(current_image) !=
(PyTypeObject *)&PyGmicImageType) {
PyErr_Format(PyExc_TypeError,
"'%.50s' input object found at "
"position %d in "
"'images' list is not a '%.400s'",
Py_TYPE(current_image)->tp_name,
image_position, PyGmicImageType.tp_name);
Py_XDECREF(input_gmic_images);
Py_XDECREF(input_gmic_image_names);
return NULL;
}
// Fill our just created gmic_list at same index
// with gmic_image coming from Python
swap_gmic_image_into_gmic_list(
(PyGmicImage *)current_image, images, image_position);
image_position++;
}
// Process images and names
((PyGmic *)self)
->_gmic->run(commands_line, images, image_names, 0, 0);
// Prevent images auto-deallocation by G'MIC
image_position = 0;
// Bring new images set back into the Python world
// (change List items in-place) First empty the input
// Python images List object from its items without
// deleting it (empty list, same reference)
PySequence_DelSlice(input_gmic_images, 0,
PySequence_Length(input_gmic_images));
cimglist_for(images, l)
{
// On the fly python GmicImage build per
// https://stackoverflow.com/questions/4163018/create-an-object-using-pythons-c-api/4163055#comment85217110_4163055
PyObject *_data = PyBytes_FromStringAndSize(
(const char *)images[l]._data,
(Py_ssize_t)sizeof(T) * images[l].size());
PyObject *new_gmic_image = NULL;
new_gmic_image = PyObject_CallFunction(
(PyObject *)&PyGmicImageType,
// The last argument is a p(redicate), ie.
// boolean..
// but Py_BuildValue() used by
// PyObject_CallFunction has a slightly
// different parameters format specification
(const char *)"SIIIIi", _data,
(unsigned int)images[l]._width,
(unsigned int)images[l]._height,
(unsigned int)images[l]._depth,
(unsigned int)images[l]._spectrum,
(int)images[l]._is_shared);
if (new_gmic_image == NULL) {
PyErr_Format(
PyExc_RuntimeError,
"Could not initialize GmicImage for "
"appending "
"it to provided 'images' parameter list.");
return NULL;
}
PyList_Append(input_gmic_images, new_gmic_image);
}
// B/ Else if a single GmicImage was provided
}
else if (Py_TYPE(input_gmic_images) ==
(PyTypeObject *)&PyGmicImageType) {
images.assign(1);
swap_gmic_image_into_gmic_list(
(PyGmicImage *)input_gmic_images, images, 0);
// Pipe the commands, our single image, and no image
// names
((PyGmic *)self)
->_gmic->run(commands_line, images, image_names, 0, 0);
// Alter the original image only if the gmic_image list
// has not been downsized to 0 elements this may happen
// with eg. a rm[0] G'MIC command We must prevent this,
// because a 'core dumped' happens otherwise
if (images.size() > 0) {
swap_gmic_list_item_into_gmic_image(
images, 0, (PyGmicImage *)input_gmic_images);
}
else {
PyErr_Format(PyExc_RuntimeError,
"'%.50s' 'images' single-element parameter "
"was removed by your G\'MIC command. It was "
"probably emptied, your optional "
"'image_names' list is untouched.",
Py_TYPE(input_gmic_images)->tp_name,
PyGmicImageType.tp_name,
PyGmicImageType.tp_name);
Py_XDECREF(input_gmic_images);
Py_XDECREF(input_gmic_image_names);
return NULL;
}
}
// Else if provided 'images' type is unknown, raise Error
else {
PyErr_Format(PyExc_TypeError,
"'%.50s' 'images' parameter must be a "
"'%.400s', or list "
"of either '%.400s'(s)",
Py_TYPE(input_gmic_images)->tp_name,
PyGmicImageType.tp_name, PyGmicImageType.tp_name);
Py_XDECREF(input_gmic_images);
Py_XDECREF(input_gmic_image_names);
return NULL;
}
// If a correctly-typed image names parameter was provided,
// even if wrongly typed, let us update its Python object
// in place, to mirror any kind of changes that may have
// taken place in the gmic_list of image names
if (input_gmic_image_names != NULL) {
// i) If a list parameter was provided
if (PyList_Check(input_gmic_image_names)) {
// First empty the input Python image names list
PySequence_DelSlice(
input_gmic_image_names, 0,
PySequence_Length(input_gmic_image_names));
// Add image names from the Gmic List of names
cimglist_for(image_names, l)
{
PyList_Append(input_gmic_image_names,
PyUnicode_FromString(image_names[l]));
}
}
// ii) If a str parameter was provided
// Because of Python's string immutability, we will not
// change the input string's content here :) :/
}
}
else { // If no gmic_images given
T pixel_type;
((PyGmic *)self)
->_gmic->run((const char *const)commands_line,
(float *const)NULL, (bool *const)NULL,
(const T &)pixel_type);
}
Py_XDECREF(input_gmic_images);
Py_XDECREF(input_gmic_image_names);
}
catch (gmic_exception &e) {
PyErr_SetString(GmicException, e.what());
return NULL;
}
catch (std::exception &e) {
PyErr_SetString(GmicException, e.what());
return NULL;
}
#ifdef gmic_py_jupyter_ipython_display
// Use a special way of displaying only if the OS's display is not
// available
if (no_display_available) {
// Provide a fallback for gmic "display" command (without
// supporting arguments) The idea is to replace all occurences
// of "display" by "output someprefix.png display in ipython
ipython_matplotlib_display_result =
gmic_py_display_with_matplotlib_or_ipython(
PyList_GetItem(commands_line_display_to_ouput_result, 1));
if (ipython_matplotlib_display_result == NULL) {
// If we are not within a IPython environment, this is OK
// Let us just print the exception without throwing it further
// This case typically happens in readthedocs.org for gmic-sphinx
PyErr_Print();
}
}
Py_XDECREF(commands_line_display_to_ouput_result);
Py_XDECREF(ipython_matplotlib_display_result);
#endif
Py_RETURN_NONE;
}
#ifdef gmic_py_numpy
/**
* Predictable Python 3.x 'numpy' module importer.
*/
PyObject *
import_numpy_module()
{
PyObject *numpy_module = PyImport_ImportModule("numpy");
// exit raising numpy_module import exception
if (!numpy_module) {
PyErr_Clear();
return PyErr_Format(GmicException,
"The 'numpy' module cannot be imported. Is it "
"installed or in your Python path?");
}
return numpy_module;
}
/*
* GmicImage class method from_numpy_helper().
* This factory class method generates a G'MIC Image from a
* numpy.ndarray.
*
* GmicImage.from_numpy_helper(obj: numpy.ndarray, deinterleave=True,
* permute="xyzc": bool) -> GmicImage
*/
static PyObject *
PyGmicImage_from_numpy_helper(PyObject *cls, PyObject *args, PyObject *kwargs)
{
PyObject *py_arg_deinterleave = NULL;
PyObject *py_arg_deinterleave_default =
Py_True; // Will deinterleave the incoming numpy.ndarray by default
PyObject *py_arg_ndarray = NULL;
PyObject *ndarray_type = NULL;
unsigned int ndarray_ndim = 0;
PyObject *ndarray_dtype = NULL;
PyObject *ndarray_dtype_kind = NULL;
PyObject *float32_ndarray = NULL;
PyObject *ndarray_as_3d_unsqueezed_view = NULL;
PyObject *ndarray_as_3d_unsqueezed_view_expanded_dims = NULL;
PyObject *ndarray_shape_tuple = NULL;
unsigned int _width = 1, _height = 1, _depth = 1, _spectrum = 1;
PyObject *numpy_module = NULL;
PyObject *ndarray_data_bytesObj = NULL;
T *ndarray_data_bytesObj_ptr = NULL;
char const *keywords[] = {"numpy_array", "deinterleave", "permute", NULL};
PyGmicImage *py_gmicimage_to_fill = NULL;
char *arg_permute = NULL;
numpy_module = import_numpy_module();
if (!numpy_module)
return NULL;
ndarray_type = PyObject_GetAttrString(numpy_module, "ndarray");
if (!PyArg_ParseTupleAndKeywords(
args, kwargs, (const char *)"O!|O!s", (char **)keywords,
(PyTypeObject *)ndarray_type, &py_arg_ndarray, &PyBool_Type,
&py_arg_deinterleave, &arg_permute))
return NULL;
py_arg_deinterleave = py_arg_deinterleave == NULL
? py_arg_deinterleave_default
: py_arg_deinterleave;
Py_XINCREF(py_arg_ndarray);
Py_XINCREF(py_arg_deinterleave);
// Get number of dimensions and ensure we are >=1D <=4D
ndarray_ndim = (unsigned int)PyLong_AsSize_t(
PyObject_GetAttrString(py_arg_ndarray, "ndim"));
if (ndarray_ndim < 1 || ndarray_ndim > 4) {
PyErr_Format(GmicException,
"Provided 'data' of type 'numpy.ndarray' must be between "
"1D and 4D ('data.ndim'=%d).",
ndarray_ndim);
return NULL;
}
// Get input ndarray.dtype and prevent non-integer/float/bool data
// types to be processed
ndarray_dtype = PyObject_GetAttrString(py_arg_ndarray, "dtype");
// Ensure dtype kind is a number we can convert (from dtype values
// here:
// https://numpy.org/doc/1.18/reference/generated/numpy.dtype.kind.html#numpy.dtype.kind)
ndarray_dtype_kind = PyObject_GetAttrString(ndarray_dtype, "kind");
if (strchr("biuf", (PyUnicode_ReadChar(ndarray_dtype_kind,
(Py_ssize_t)0))) == NULL) {
PyErr_Format(PyExc_TypeError,
"Parameter 'data' of type 'numpy.ndarray' does not "
"contain numbers ie. its 'dtype.kind'(=%U) is not one of "
"'b', 'i', 'u', 'f'.",
ndarray_dtype_kind);
// TODO pytest this
return NULL;
}
// Using an 'ndarray.astype' array casting operation first into
// G'MIC's core point type T <=> float32 With a
// memory-efficient-'ndarray.view' instead of copy-obligatory
// 'ndarray.astype' conversion, we might get the following error:
// ValueError: When changing to a larger dtype, its size must be a
// divisor of the total size in bytes of the last axis of the
// array. So, using 'astype' is the most stable, less
// memory-efficient way
// :-) :-/
float32_ndarray =
PyObject_CallMethod(py_arg_ndarray, "astype", "O",
PyObject_GetAttrString(numpy_module, "float32"));
// Get unsqueezed shape of numpy array -> GmicImage width, height,
// depth, spectrum Getting a shape with the most axes from array:
// https://docs.scipy.org/doc/numpy-1.17.0/reference/generated/numpy.atleast_3d.html#numpy.atleast_3d
// Adding a depth axis using numpy.expand_dims:
// https://docs.scipy.org/doc/numpy-1.17.0/reference/generated/numpy.expand_dims.html
// (numpy tends to squeeze dimensions when calling the standard
// array().shape, we circumvent this)
ndarray_as_3d_unsqueezed_view =
PyObject_CallMethod(numpy_module, "atleast_3d", "O", float32_ndarray);
ndarray_as_3d_unsqueezed_view_expanded_dims = PyObject_CallMethod(
numpy_module, "expand_dims", "OI", ndarray_as_3d_unsqueezed_view,
2); // Adding z axis if absent
// After this the shape should be (w, h, 1, 3)
ndarray_shape_tuple = PyObject_GetAttrString(
ndarray_as_3d_unsqueezed_view_expanded_dims, "shape");
_height =
(unsigned int)PyLong_AsSize_t(PyTuple_GetItem(ndarray_shape_tuple, 0));
_width =
(unsigned int)PyLong_AsSize_t(PyTuple_GetItem(ndarray_shape_tuple, 1));
_depth =
(unsigned int)PyLong_AsSize_t(PyTuple_GetItem(ndarray_shape_tuple, 2));
_spectrum =
(unsigned int)PyLong_AsSize_t(PyTuple_GetItem(ndarray_shape_tuple, 3));
py_gmicimage_to_fill = (PyGmicImage *)PyObject_CallFunction(
(PyObject *)&PyGmicImageType, (const char *)"OIIII",
Py_None, // This empty _data buffer will be regenerated by the
// GmicImage constructor as a zero-filled bytes
// object
_width, _height, _depth, _spectrum);
ndarray_data_bytesObj =
PyObject_CallMethod(ndarray_as_3d_unsqueezed_view, "tobytes", NULL);
ndarray_data_bytesObj_ptr = (T *)PyBytes_AsString(ndarray_data_bytesObj);
// no deinterleaving
if (!PyObject_IsTrue(py_arg_deinterleave)) {
for (unsigned int c = 0; c < _spectrum; c++) {
for (unsigned int z = 0; z < _depth; z++) {
for (unsigned int y = 0; y < _height; y++) {
for (unsigned int x = 0; x < _width; x++) {
(*(py_gmicimage_to_fill->_gmic_image))(x, y, z, c) =
*(ndarray_data_bytesObj_ptr++);
}
}
}
}
}
else { // deinterleaving
for (unsigned int z = 0; z < _depth; z++) {
for (unsigned int y = 0; y < _height; y++) {
for (unsigned int x = 0; x < _width; x++) {
for (unsigned int c = 0; c < _spectrum; c++) {
(*(py_gmicimage_to_fill->_gmic_image))(x, y, z, c) =
*(ndarray_data_bytesObj_ptr++);
}
}
}
}
}
Py_XDECREF(py_arg_ndarray);
Py_XDECREF(py_arg_deinterleave);
Py_XDECREF(ndarray_dtype);
Py_XDECREF(ndarray_dtype_kind);
Py_XDECREF(float32_ndarray);
Py_XDECREF(ndarray_as_3d_unsqueezed_view);
Py_XDECREF(ndarray_as_3d_unsqueezed_view_expanded_dims);
Py_XDECREF(ndarray_shape_tuple);
Py_XDECREF(ndarray_data_bytesObj);
Py_XDECREF(ndarray_type);
Py_XDECREF(numpy_module);
return (PyObject *)py_gmicimage_to_fill;
}
static PyObject *
PyGmicImage_from_numpy(PyObject *cls, PyObject *args, PyObject *kwargs)
{
char const *keywords[] = {"numpy_array", NULL};
PyObject *arg_np_array = NULL; // No defaults
PyObject *a = NULL;