-
Notifications
You must be signed in to change notification settings - Fork 2
/
PhotonFile.py
1940 lines (1619 loc) · 87.4 KB
/
PhotonFile.py
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
"""
Loads/Save .photon files (from the Anycubic Photon Slicer) in memory and allows editing of settings and bitmaps.
Version: 25 jun 2019
Author: Nard Janssens
Todo:
edit getBitmap2
fix layerheight on layers.delete and insert
flip layers(tack) x-y, hor, vertical
show footprint of stack....combine layers to image using gray scale
"""
# Style Guide:
# module_name, package_name, ClassName, method_name,
# ExceptionName, function_name,
# GLOBAL_CONSTANT_NAME, global_var_name, instance_var_name,
# function_parameter_name, local_var_name
__version__ = "alpha"
__author__ = "Nard Janssens, Vinicius Silva, Robert Gowans, Ivan Antalec, Leonardo Marques - See Github PhotonFileUtils"
import os
import sys
import copy
import math
import struct
from math import *
import time
import multiprocessing
import time
import RLE
try:
import numpy
numpyAvailable = True
#print("Numpy library available.")
except ImportError:
numpyAvailable = False
raise Exception ("PhotonFile needs the numpy library!")
#print ("Numpy library not found.")
try:
import cv2
cv2Available = True
#print("Numpy library available.")
except ImportError:
cv2Available = False
raise Exception ("PhotonFile needs the OpenCV2 library!")
#print ("Numpy library not found.")
########################################################################################################################
## Define Data Types
#########################################################################################################################
# Data type constants
tpByte = 0
tpChar = 1
tpInt = 2
tpFloat = 3
tpTypeNames=("byte","char","int","float")
nrFloatDigits = 4
def convBytes(bytes:bytes, bType:int):
""" Converts all photonfile types to bytes. """
nr = None
if bType == tpInt:
nr = bytes_to_int(bytes)
if bType == tpFloat:
nr = round(bytes_to_float(bytes),ndigits=nrFloatDigits)
if bType == tpByte:
nr = bytes_to_hex(bytes)
return nr
def convVal(val):
""" Converts all photonfile types to bytes. """
nr = None
if type(val) == int:
nr = int_to_bytes(val)
return nr
if type(val) == float:
nr = float_to_bytes(val)
return nr
raise Exception("PhotonFile.convVal received unhandled var type",type(val),"!")
########################################################################################################################
## File structure
########################################################################################################################
# This is the data structure of photon file. For each variable we need to know
# Title string to display user, nr bytes to read/write, type of data stored, editable
# Each file consists of
# - General info ( pfStruct_Header, Header)
# - Two previews which contain meta-info an raw image data ( pfStruct_Previews, Previews)
# - For each layer meta-info ( pfStruct_LayerDef, LayerDefs)
# - For each layer raw image data ( pfStruct_LayerData, LayerData)
nrLayersString = "# Layers" #String is used in multiple locations and thus can be edited here
pfStruct_Header = [
("Header", 8, tpByte, False, ""),
("Bed X (mm)", 4, tpFloat, True, "Short side of the print bed."),
("Bed Y (mm)", 4, tpFloat, True, "Long side of the print bed."),
("Bed Z (mm)", 4, tpFloat, True, "Maximum height the printer can print."),
["padding", 3 * 4, tpByte, False, ""], # 3 ints
("Layer height (mm)", 4, tpFloat, True, "Default layer height."),
("Exp. time (s)", 4, tpFloat, True, "Default exposure time."),
("Exp. bottom (s)", 4, tpFloat, True, "Exposure time for bottom layers."),
("Off time (s)", 4, tpFloat, True, "Time UV is turned of between layers. \n Minimum is 6.5 sec, the time to rise the \n build plate and dip back in the resin."),
("# Bottom Layers", 4, tpInt, True, "Number of bottom layers.\n (These have different exposure time.)"),
("Resolution X", 4, tpInt, True, "X-Resolution of the screen through \n which the layer image is projected."),
("Resolution Y", 4, tpInt, True, "Y-Resolution of the screen through \n which the layer image is projected." ),
("Preview 0 (addr)", 4, tpInt, False, "Address where the metadata \n of the High Res preview image can be found."), # start of preview 0
("Layer Defs (addr)", 4, tpInt, False, "Address where the metadata \n for the layer images can be found."), # start of layerDefs
(nrLayersString, 4, tpInt, False, "Number of layers this file has."),
("Preview 1 (addr)", 4, tpInt, False, "Address where the metadata of the \n Low Res preview image can be found."), # start of preview 1
("unknown6", 4, tpInt, False, ""),
("Proj.type-Cast/Mirror", 4, tpInt, False, "LightCuring/Projection type:\n 1=LCD_X_MIRROR \n 0=CAST"), #LightCuring/Projection type // (1=LCD_X_MIRROR, 0=CAST)
["padding tail", 6 * 4, tpByte, False, ""] # 6 ints
]
pfStruct_Previews = [
("Resolution X", 4, tpInt, False, "X-Resolution of preview pictures."),
("Resolution Y", 4, tpInt, False, "Y-Resolution of preview pictures."),
("Image Address", 4, tpInt, False, "Address where the raw \n image can be found."), # start of rawData0
("Data Length", 4, tpInt, False, "Size [in bytes) of the \n raw image."), # size of rawData0
["padding", 4 * 4, tpByte, False, ""], # 4 ints
("Image Data", -1, tpByte, False, "The raw image."),
["padding tail", 0, tpByte, False, ""]
]
pfStruct_Previews_Padding = ["padding", 0, tpByte, False, ""]
# The exposure time and off times are ignored by Photon printer, layerheight not and is cumulative
pfStruct_LayerDef = [
("Layer height (mm)", 4, tpFloat, True, "Height at which this layer \n should be printed."),
("Exp. time (s)", 4, tpFloat, False, "Exposure time for this layer.\n [Based on General Info.)"),
("Off time (s)", 4, tpFloat, False, "Off time for this layer.\n (Based on General Info.)"),
("Image Address", 4, tpInt, False, "Address where the raw image \n can be found."),#dataStartPos -> Image Address
("Data Length", 4, tpInt, False, "Size (in bytes) of the raw image."), #size of rawData+lastByte(1)
["padding tail", 4 * 4, tpByte, False, ""] # 4 ints
]
pfStruct_LayerDefs_Padding = ["padding", 0, tpByte, False, ""]
pfStruct_LayerData = [
("Raw", -1, tpByte, True, "rle encoded bytes"),
["padding tail", 0, tpByte, False, ""]
]
pfStruct_LayerDatas_Padding = ["padding", 0, tpByte, False, ""] # after all Datas until end of file
KNOWN_SIGNATURES={
"H-12-24 / P0-16-0 / Pt-0 / L0-16 / Lt-0 / D0-0 / Dt-0":"ACPhotonSlicer",
"H-12-28 / P0-16-0 / Pt-60 / L0-16 / Lt-0 / D0-0 / Dt-0":"ChituBox 1.4.0"
}
layerForecolor=(167,34,252)
def get_pfStructProp(pfStruct,name:str):
for prop in pfStruct:
(bTitle, bNr, bType, bEditable,bHint) = prop
if bTitle==name: return prop
return None
def set_pfStruct(signatureName:str):
PROP_LENGTH=1
for sign_id,sign_name in KNOWN_SIGNATURES.items():
if signatureName==sign_name:
vals = sign_id.split("/")
get_pfStructProp(pfStruct_Header,"padding")[PROP_LENGTH]=int(vals[0].split('-')[1])
get_pfStructProp(pfStruct_Header,"padding tail")[PROP_LENGTH]=int(vals[0].split('-')[2])
get_pfStructProp(pfStruct_Previews,"padding")[PROP_LENGTH]=int(vals[1].split('-')[1])
get_pfStructProp(pfStruct_Previews,"padding tail")[PROP_LENGTH]=int(vals[1].split('-')[2])
pfStruct_Previews_Padding [PROP_LENGTH] = int(vals[2].split('-')[1])
get_pfStructProp(pfStruct_LayerDef,"padding tail")[PROP_LENGTH]=int(vals[3].split('-')[1])
pfStruct_LayerDefs_Padding [PROP_LENGTH] = int(vals[4].split('-')[1])
get_pfStructProp(pfStruct_LayerData,"padding tail")[PROP_LENGTH] = int(vals[5].split('-')[1])
pfStruct_LayerDatas_Padding [PROP_LENGTH] = int(vals[6].split('-')[1])
########################################################################################################################
## Convert byte string to hex string
########################################################################################################################
def retrieve_name(var):
import inspect
callers_local_vars = inspect.currentframe().f_back.f_locals.items()
return [var_name for var_name, var_val in callers_local_vars if var_val is var]
def debugp(var):
print (retrieve_name(var),":",var)
########################################################################################################################
## Convert byte string to hex string
########################################################################################################################
def hexStr(bytes:bytes):
if isinstance(bytes, bytearray):
return ' '.join(format(h, '02X') for h in bytes)
if isinstance(bytes, int):
return format(bytes, '02X')
return ("No Byte (string)")
########################################################################################################################
## Methods to convert bytes (strings) to python variables and back again
########################################################################################################################
def bytes_to_int(bytes:bytes):
""" Converts list or array of bytes to an int. """
result = 0
for b in reversed(bytes):
result = result * 256 + int(b)
return result
def bytes_to_float(inbytes:bytes):
""" Converts list or array of bytes to an float. """
bits = bytes_to_int(inbytes)
mantissa = ((bits & 8388607) / 8388608.0)
exponent = (bits >> 23) & 255
sign = 1.0 if bits >> 31 == 0 else -1.0
if exponent != 0:
mantissa += 1.0
elif mantissa == 0.0:
return sign * 0.0
return sign * pow(2.0, exponent - 127) * mantissa
def bytes_to_hex(bytes:bytes):
""" Converts list or array of bytes to an hex. """
return ' '.join(format(h, '02X') for h in bytes)
def hex_to_bytes(hexStr:str):
""" Converts hex to array of bytes. """
return bytearray.fromhex(hexStr)
def int_to_bytes(intVal:int):
""" Converts POSITIVE int to bytes. """
return intVal.to_bytes(4, byteorder='little')
def float_to_bytes(floatVal:float):
""" Converts POSITIVE floats to bytes.
Based heavily upon http: //www.simplymodbus.ca/ieeefloats.xls
"""
# Error when floatVal=0.5
return struct.pack('f',floatVal)
if floatVal == 0: return (0).to_bytes(4, byteorder='big')
sign = -1 if floatVal < 0 else 1
firstBit = 0 if sign == 1 else 1
exponent = -127 if abs(floatVal) < 1.1754943E-38 else floor(log(abs(floatVal), 10) / log(2, 10))
exponent127 = exponent + 127
mantissa = floatVal / pow(2, exponent) / sign
substract = mantissa - 1
multiply = round(substract * 8388608)
div256_1 = multiply / 256
divint_1 = int(div256_1)
rem_1 = int((div256_1 - divint_1) * 256)
div256_2 = divint_1 / 256
divint_2 = int(div256_2)
rem_2 = int((div256_2 - divint_2) * 256)
bin1 = (exponent127 & 0b11111110) >> 1 | firstBit << 7
bin2 = (exponent127 & 0b00000001) << 7 | divint_2
bin3 = rem_2
bin4 = rem_1
# print ("ALT: ",bin(bin1_new), bin(bin2_new),bin(bin3_new),bin(bin4_new))
bin1234 = bin1 | bin2 << 8 | bin3 << 16 | bin4 << 24
return bin1234.to_bytes(4, byteorder='big')
########################################################################################################################
## Class PreviewOps
########################################################################################################################
class PreviewOps:
'''
This is an internal class to provide nicely structures PhotonFile class
All methods are provided to user via PhotonFile.previews interface
- PhotonFile.previews.get (previewNr,retType)-> PIL.Image, byte array,numpy,Pygame.Surface
- PhotonFile.previews.save (previewNr,file)
- PhotonFile.previews.replace (previewNr,file/image/numpy/surface/bytearray)
- PhotonFile.previews.__decodeRLE224bImage(rleData:bytes,w:int,h:int)
- PhotonFile.layers.__previewPropType(propID:str)->int:
- PhotonFile.layers.setProperty(previewNr,idString,value)
- PhotonFile.layers.getProperty(previewNr,idString)
'''
import PhotonFile
photonfile:PhotonFile=None
Previews:[{},{}]=None
def __init__(self, photonfile:PhotonFile,Previews:[{},{}]):
""" Just stores photon filename. """
self.photonfile = photonfile
self.Previews=Previews
assert (self.Previews != [{},{}])
def __encode24bImage2RLE(self,filename:str) -> bytes:
""" Converts image data from file on disk to RLE encoded byte string.
Processes pixels one at a time (pygame.get_at) - Slow
Encoding scheme:
The color (R,G,B) of a pixel spans 2 bytes (little endian) and each color component is 5 bits: RRRRR GGG GG X BBBBB
If the X bit is set, then the next 2 bytes (little endian) masked with 0xFFF represents how many more times to repeat that pixel.
"""
image = cv2.imread(filename)
# bitDepth = imgsurf.get_bitsize()
# bytePerPixel = imgsurf.get_bytesize()
width=image.shape[1]
height=image.shape[0]
print (image.shape,width,height)
#print ("Size:", width, height)
#Preview images tend to have different sizes. Check on size is thus not possible.
#if checkSizeForNr==0 and not (width, height) == (360,186):
# raise Exception("Your image dimensions are off and should be 360x186 for the 1st preview.")
#if checkSizeForNr==1 and not (width, height) == (198,101):
# raise Exception("Your image dimensions are off and should be 198x101 for the 1st preview.")
# Count number of pixels with same color up until 0x7D/125 repetitions
rleData = bytearray()
color = 0
black = 0
white = 1
nrOfColor = 0
prevColor = None
for y in range(height):
for x in range(width):
#print (x,y)
# print (imgsurf.get_at((x, y)))
color = image[y, x] # (r, g, b, a)
if prevColor is None: prevColor = color
isLastPixel = (x == (width - 1) and y == (height - 1))
#print ("prevColor",type(prevColor),prevColor)
#print ("color",type(color),color)
if (color == prevColor).all() and nrOfColor < 0x0FFF and not isLastPixel:
nrOfColor = nrOfColor + 1
else:
# print (color,nrOfColor,nrOfColor<<1)
R=prevColor[0]
G=prevColor[1]
B=prevColor[2]
if nrOfColor>1:
X=1
else:
X=0
# build 2 or 4 bytes (depending on X
# The color (R,G,B) of a pixel spans 2 bytes (little endian) and
# each color component is 5 bits: RRRRR GGG GG X BBBBB
R = int(round(R / 255 * 31))
G = int(round(G / 255 * 31))
B = int(round(B / 255 * 31))
#print ("X,r,g,b",X,R,G,B)
encValue0=R<<3 | G>>2
encValue1=(((G & 0b00000011)<<6) | X<<5 | B)
if X==1:
nrOfColor=nrOfColor-1 # write one less than nr of pixels
encValue2=nrOfColor>>8
encValue3=nrOfColor & 0b000000011111111
#seems like nr bytes pixels have 0011 as start
encValue2=encValue2 | 0b00110000
# save bytes
rleData.append(encValue1)
rleData.append(encValue0)
if X==1:
rleData.append(encValue3)
rleData.append(encValue2)
# search next color
prevColor = color
nrOfColor = 1
#print ("len",len(rleData))
return (width,height,bytes(rleData))
def __decodeRLE2Image24b(self,rleData,w:int,h:int) -> numpy.ndarray:
# Make room for new image
imgArray=numpy.zeros((w,h,3),dtype=numpy.uint8)
# Decode bytes to colors and draw lines of that color on the pygame surface
idx = 0
pixelIdx = 0
while idx < len(rleData):
# Combine 2 bytes Little Endian so we get RRRRR GGG GG X BBBBB (and advance read byte counter)
b12 = rleData[idx + 1] << 8 | rleData[idx + 0]
idx += 2
# Retrieve colr components and make pygame color tuple
#red = round(((b12 >> 11) & 0x1F) / 31 * 255)
red = round(((b12 >> 11) & 0x1F) << 3 )
#green = round(((b12 >> 6) & 0x1F) / 31 * 255)
green = round(((b12 >> 6) & 0x1F) << 3 )
#blue = round(((b12 >> 0) & 0x1F) / 31 * 255)
blue = round((b12 & 0x1F) << 3 )
col = (red, green, blue)
# If the X bit is set, then the next 2 bytes (little endian) masked with 0xFFF represents how many more times to repeat that pixel.
nr = 1
if b12 & 0x20:
nr12 = rleData[idx + 1] << 8 | rleData[idx + 0]
idx += 2
nr += nr12 & 0x0FFF
# Draw (nr) many pixels of the color
for i in range(0, nr, 1):
x = int((pixelIdx % w))
y = int((pixelIdx / w))
imgArray[x,y,0]=red
imgArray[x,y,1]=green
imgArray[x,y,2]=blue
pixelIdx += 1
return imgArray
def get(self, prevNr:int, retType:str='i')->(bytes,numpy.ndarray):
""" Decodes a RLE byte array from PhotonFile object to a pygame surface.
Based on https://github.com/Reonarudo/pcb2photon/issues/2
Encoding scheme:
The color (R,G,B) of a pixel spans 2 bytes (little endian) and each color component is 5 bits: RRRRR GGG GG X BBBBB
If the X bit is set, then the next 2 bytes (little endian) masked with 0xFFF represents how many more times to repeat that pixel.
"""
# Tell PhotonFile we are drawing so GUI can prevent too many calls on getBitmap
self.photonfile.isDrawing = True
# Retrieve resolution of preview image and set pygame surface to that size.
w = bytes_to_int(self.photonfile.Previews[prevNr]["Resolution X"])
h = bytes_to_int(self.photonfile.Previews[prevNr]["Resolution Y"])
s = bytes_to_int(self.photonfile.Previews[prevNr]["Data Length"])
# Retrieve raw image data and add last byte to complete the byte array
rleData = self.photonfile.Previews[prevNr]["Image Data"]
numpyArray2Duint8RGB=self.__decodeRLE2Image24b(rleData,w,h)
if retType[0]=='r': #byte array
return rleData
if retType[0]=='b': #byte array
return numpyArray2Duint8RGB.tobytes()
if retType[0]=='n': #numpy
return numpyArray2Duint8RGB
if retType[0]=='i': #cv2.Image
return numpyArray2Duint8RGB
# Done drawing so next caller knows that next call can be made.
self.isDrawing = False
raise Exception("Preview.get needs you to specify a return type (rle,bytes, numpy, Image, Surface).")
def save(self, filepath:str, previewNr:int) -> None:
""" Saves specified preview image in PhotonFile object as (decoded) png files in specified directory and with file precursor"""
# Get the preview images
image = self.get(previewNr,retType='image') # 0 is don't scale
# Save preview image to disk
cv2.imwrite(filepath,image)
return
def replace(self, previewNr:int,filepath:str) -> None:
""" Replace image data in PhotonFile object with new (encoded data of) image on disk."""
# Get/encode raw data
(width,height,rawData) = self.__encode24bImage2RLE(filepath)
if len(rawData)==0:
raise Exception ("Preview.replace got not import image.")
# Get change in image rawData size so we can correct starting addresses of higher layer images
oldLength=bytes_to_int(self.photonfile.Previews[previewNr]["Data Length"]) #"Data Length" = len(rawData)+len(EndOfLayer)
newLength=len(rawData)
deltaLength=newLength-oldLength
#print ("old, new, delta:",oldLength,newLength,deltaLength)
# Update image settings and raw data of layer to be replaced
self.photonfile.Previews[previewNr]["Resolution X"]= int_to_bytes(width)
self.photonfile.Previews[previewNr]["Resolution Y"]= int_to_bytes(height)
self.photonfile.Previews[previewNr]["Data Length"] = int_to_bytes(len(rawData))
self.photonfile.Previews[previewNr]["Image Data"] = rawData
# Update Header info about "Preview 1 (addr)"
if previewNr==0: # then the "Preview 1 (addr)" shifts
curAddr=bytes_to_int(self.photonfile.Header["Preview 1 (addr)"])
newAddr = curAddr + deltaLength
self.photonfile.Header["Preview 1 (addr)"]=int_to_bytes(newAddr)
# Update Preview[1] info about "Preview 1 (addr)"
curAddr=bytes_to_int(self.photonfile.Previews[1]["Image Address"])
newAddr = curAddr + deltaLength
self.photonfile.Previews[1]["Image Address"]=int_to_bytes(newAddr)
#Always Header info about layerdefs shifts
curAddr = bytes_to_int(self.photonfile.Header["Layer Defs (addr)"])
newAddr = curAddr + deltaLength
self.photonfile.Header["Layer Defs (addr)"] = int_to_bytes(newAddr)
# Update start addresses of RawData of all following images
nLayers=self.photonfile.layers.count()
for rLayerNr in range(0,nLayers):
curAddr=bytes_to_int(self.photonfile.LayerDefs[rLayerNr]["Image Address"])
newAddr=curAddr+deltaLength
self.photonfile.LayerDefs[rLayerNr]["Image Address"]= int_to_bytes(newAddr)
def __previewPropType(self,propID:str)->int:
for bTitle, bNr, bType, bEditable,bHint in pfStruct_Previews:
if bTitle==propID:
return bType
def getProperty(self,previewNr:int,propID:str)->(float,int,bytes):
valbytes = self.photonfile.Previews[previewNr][propID]
valtype = self.__previewPropType(propID)
return convBytes(valbytes,valtype)
def setProperty(self,previewNr:int,propID:str,value):
valtype = self.__previewPropType(propID)
if (type(value) is int) and valtype==tpInt:
self.photonfile.Previews[previewNr][propID] = int_to_bytes(value)
return
if (type(value) is float) and valtype==tpFloat:
self.photonfile.Previews[previewNr][propID] = float_to_bytes(value)
return
raise Exception(f"Preview.setProperty go an invalid type passed. Property '{propID}' needs {self.photongfile.tpTypeNames[valtype]} got {type(value)}.")
########################################################################################################################
## Class LayerOps
########################################################################################################################
class LayerOps:
import PhotonFile
'''
This is an internal class to provide nicely structures PhotonFile class
All methods are provided to user via PhotonFile.layers interface
- PhotonFile.layers.__getall (retType) -> PIL.Image,bytes,numpy,Pygame.Surface
- PhotonFile.layers.__saveall (folder:str)
- PhotonFile.layers.__replaceall (images:str,list(rlestack))
- PhotonFile.layers.__headerPropType (propID:str)->int
- PhotonFile.layers.save (layerNr,file)
- PhotonFile.layers.load (dir/file, optional layernr) -> append/insert
- PhotonFile.layers.get (layerNr,retType)-> PIL.Image, byte array,numpy,Pygame.Surface
- PhotonFile.layers.insert (layerNr,file/image/numpy/surface/bytearray)
- PhotonFile.layers.delete (layerNr:int)
- PhotonFile.layers.append (file/image/numpy/surface/bytearray) (=insertBefore(nrLayers))
- PhotonFile.layers.replace (layerNr,file/image/numpy/surface/bytearray)
- PhotonFile.layers.copy (layerNr,layerNr)
- PhotonFile.layers.setProperty(layerNr,idString,value)
- PhotonFile.layers.getProperty(layerNr,idString)
- PhotonFile.layers.count()
- PhotonFile.layers.height()
- PhotonFile.layers.volume()
- PhotonFile.layers.__deepcopy(dictionary)
- PhotonFile.layers.loadFromHistory()
- PhotonFile.layers.saveFromHistory()
'''
photonfile:PhotonFile=None
LayerDefs:[]=None
LayerData:[]=None
__ALL_LAYERS:int=-1
cancelReplace:bool=False
History = []
def __init__(self, photonfile:PhotonFile, LayerDefs:[],LayerData:[]):
""" Just stores photon filename. """
self.photonfile = photonfile
self.LayerDefs=LayerDefs
self.LayerData=LayerData
self.History = []
assert (self.LayerDefs != [])
assert (self.LayerData != [])
# Internals for multithreading
def getAll(self):
''' Returns all images in the photonfile as list of rle bytearray
Memory does not allow for list of cv2.images, numpy arrays
'''
all=list()
#tstart=time.time()
for layerNr in range(self.count()):
rle=self.get(layerNr,retType='rle')
all.append(rle)
#print (f"100% - {round((time.time() - tstart),3)} sec." )
return all
def par_getBitmap(self,args):
# Helper for procespoolexecutor in replaceBitmaps to call
[layerNr,fullfilename]=args
image = self.get(layerNr,'i')
cv2.imwrite(fullfilename,image)
return layerNr
def saveAll(self,dirpath:str,filepre:str="",progressDialog=None):
'''Save all images in PhotonFile object as (decoded) png files in specified directory and with file precursor"""
Benchmark 1716 layers:
No parallel code: 30.5 sec
Multiprocessing: 14.7 sec
ThreadPool: 18.5 sec
ProcessPool: Crash/Hang
'''
# Check if dirpath is a file
if (os.path.exists(dirpath)) and not (os.path.isdir(dirpath)):
raise Exception("LayerOps.saveAll received '{dirpath}' as directory but is a file.")
# Check if directory is present
if not os.path.isdir(dirpath):
os.makedirs(dirpath)
# Recheck if directory is present (check for OS Error)
if not os.path.isdir(dirpath):
raise Exception(f"LayerOps.saveAll did not succeed in creating directory '{dirpath}'.")
# Traverse all layers
nLayers=self.count()
files=[]
for layerNr in range(0,nLayers):
nrStr = "%04d" % layerNr
filename = filepre
if filepre!='': filename=filename+"-"
filename = filename + nrStr + ".png"
fullfilename = os.path.join(dirpath, filename)
files.append([layerNr,fullfilename])
tstart=time.time()
cpus=multiprocessing.cpu_count()
pool=multiprocessing.Pool(processes=cpus-1)
r=pool.map_async(self.par_getBitmap,files)
pool.close()
#pool.join()
number_start=r._number_left
while True:
perc=round(100*(number_start-r._number_left)/number_start)
sys.stderr.write('\rExporting... ')
sys.stderr.write(str(perc))
sys.stderr.write('% ')
if progressDialog: progressDialog.setProgressPerc(perc)
time.sleep(0.5)
if (r._number_left == 0):
print (f"100% - {round((time.time() - tstart),1)} sec." )
if progressDialog: progressDialog.setProgressPerc(100)
break
return True
def par_encodeImageFile2Bytes(self,args):
# Helper for procespoolexecutor in replaceBitmaps to call
[layerNr,fullfilename]=args
npArray=cv2.imread(fullfilename)
if npArray.ndim==3:
npArray=npArray[:,:,0]
npArray_1D_uint8=npArray.flatten().astype(numpy.uint8)
rlebytes= RLE.encode8bImage2RLE(npArray_1D_uint8)
#return [layerNr,rlebytes] # results are presented to callback in order, layerNr is not needed
return rlebytes # results are presented to callback in order, layerNr is not needed
def replaceAll(self,images:(str,list),progressDialog=None):
''' Replaces all layer images with png-images available in a folder on disk.
Images is string for folder with png or
Images is list of rle bytearrays
'''
if type(images)==str: # directory with files
dirPath=images
rlestack=()
# Find all png files
direntries = os.listdir(dirPath)
files = []
for entry in direntries:
fullpath = os.path.join(dirPath, entry)
if entry.endswith("png"):
if not entry.startswith("_"): # on a export of images from a photon file, the preview image starts with _
files.append(fullpath)
files.sort()
# We need a list of tuples consisting of (layerNr,filename)
files=list(enumerate(files))
# Check if there are files available and if so check first file for correct dimensions
if len(files) == 0: raise Exception("LayerOps.__replaceAll cannot find any files of type png!")
# Read all files in parallel and wait for result
nLayers=len(files)
rlestack = nLayers * [None]
tstart=time.time()
cpus=multiprocessing.cpu_count()
pool=multiprocessing.Pool(processes=cpus-1)
# results should not be reteived using callback (then we need some routine to check if all is finished)
r=pool.map_async(self.par_encodeImageFile2Bytes,files)
pool.close()
number_start=r._number_left
while True:
perc=round(100*(number_start-r._number_left)/number_start)
sys.stderr.write('\rImporting... ')
sys.stderr.write(str(perc))
sys.stderr.write('% ')
if progressDialog: progressDialog.setProgressPerc(perc)
time.sleep(0.5)
if (r._number_left == 0): # updates are less than 2x per second
print (f"100% - {round((time.time() - tstart),1)} sec." )
if progressDialog: progressDialog.setProgressPerc(100)
self.replaceAll(r.get(None))
break
return
if isinstance(images,list): # list of rleByteArray
if not isinstance(images[0],bytes):
raise Exception("LayerOps.__replaceAll only accepts a list of RLE byte arrays due to memory constraints.")
rleStack=images
self.clear()
for rleData in rleStack:
self.append(rleData)
# Check
for layerNr in range(self.count()-1):
a0=bytes_to_int(self.photonfile.LayerDefs[layerNr+0]["Image Address"])
l=bytes_to_int(self.photonfile.LayerDefs[layerNr+0]["Data Length"])
a1=bytes_to_int(self.photonfile.LayerDefs[layerNr+1]["Image Address"])
d=len(self.photonfile.LayerData[layerNr]["Raw"])
t=len(self.photonfile.LayerData[layerNr]["padding tail"])
if d!=l:
assert(True==False)
if (a1-a0)!=(d+t):
assert(True==False)
if (a1-a0)!=l:
assert(True==False)
return
# If we reach this point, we did not get a string or a list as input
raise Exception("LayerOps.__replaceAll will only convert files on disk or a list of rle encoded bytestrings.")
nr=0
# User functions
def __layerPropType(self,propID:str)->int:
for bTitle, bNr, bType, bEditable,bHint in pfStruct_LayerDef:
if bTitle==propID:
return bType
def getProperty(self,layerNr:int,propID:str):
valbytes = self.photonfile.LayerDefs[layerNr][propID]
valtype = self.__layerPropType(propID)
return convBytes(valbytes,valtype)
def setProperty(self,layerNr:int,propID:str,value):
valtype = self.__layerPropType(propID)
if (type(value) is int) and valtype==tpInt:
self.photonfile.LayerDefs[layerNr][propID] = int_to_bytes(value)
return
if (type(value) is float) and valtype==tpFloat:
self.photonfile.LayerDefs[layerNr][propID] = float_to_bytes(value)
return
raise Exception(f"LayerOps.setProperty got an invalid type passed. Property '{propID}' needs {self.photonfile.tpTypeNames[valtype]} got {type(value)}.")
def print(self,layerNr:int):
print ("Layer Nr",layerNr)
print (" Layer height (mm): ",bytes_to_float(self.photonfile.LayerDefs[layerNr]["Layer height (mm)"]))
print (" Exp. time (s) : ",bytes_to_float(self.photonfile.LayerDefs[layerNr]["Exp. time (s)"]))
print (" Off time (s) : ",bytes_to_float(self.photonfile.LayerDefs[layerNr]["Off time (s)"]))
print (" Image Address : ",bytes_to_int(self.photonfile.LayerDefs[layerNr]["Image Address"]))
print (" Data Length : ",bytes_to_int(self.photonfile.LayerDefs[layerNr]["Data Length"]))
print (" def padding tail : ",len(self.photonfile.LayerDefs[layerNr]["padding tail"]),"'"+bytes_to_hex(self.photonfile.LayerDefs[layerNr]["padding tail"])+"'")
print (" Raw length) : ",len(self.photonfile.LayerData[layerNr]["Raw"]))
print (" Raw padding tail : ",len(self.photonfile.LayerData[layerNr]["padding tail"]),"'"+bytes_to_hex(self.photonfile.LayerData[layerNr]["padding tail"])+"'")
def count(self):
""" Returns 4 bytes for number of layers as int. """
return bytes_to_int(self.photonfile.Header[nrLayersString])
def last(self):
""" Returns 4 bytes for number of layers as int. """
return self.count()-1
def height(self,layerNr:int):
""" Return height between two layers
"""
# We retrieve layer height from previous layer
if layerNr>0:
curLayerHeight = convBytes(self.photonfile.LayerDefs[layerNr]["Layer height (mm)"],tpFloat)
prevLayerHeight = convBytes(self.photonfile.LayerDefs[layerNr-1]["Layer height (mm)"],tpFloat)
else:
if self.count()>1:
curLayerHeight = convBytes(self.photonfile.LayerDefs[layerNr+1]["Layer height (mm)"],tpFloat)
prevLayerHeight=0
else:
curLayerHeight=convBytes(self.photonfile.Header["Layer height (mm)"],tpFloat)
prevLayerHeight = 0
return curLayerHeight-prevLayerHeight
#print ("Delta:", deltaHeight)
def load(self,path:str,layerNr:int,operation:str='append',saveToHistory=True):
''' operation: 'append' / 'replace'
'''
if operation[0]=='r':
self.replace(layerNr,path,saveToHistory=True)
return
if operation[0]=='a':
self.append(path,saveToHistory=True)
return
if layerNr==self.__ALL_LAYERS:
self.replaceAll(path)
return
raise Exception("LayerOps.load got an invalid operation. Use 'append' or 'replace'.")
def save(self,layerNr:int, path:str):
if layerNr==self.__ALL_LAYERS:
self.saveAll(path)
else:
nrStr = "%04d" % layerNr
if self.photonfile.filename!=None:
filepre = os.path.join(path,os.path.basename(self.photonfile.filename))
else:
filepre = os.path.join(path,"newfile")
fullfilename = filepre + "-" + nrStr + ".png"
print ("fullfilename",fullfilename)
image=self.get(layerNr,retType='i')
cv2.imwrite(fullfilename,image)
def append(self,
image:(str,numpy.ndarray,bytes),
saveToHistory:bool=False):
self.insert(image,self.count(),saveToHistory)
def paste (self,layerNr:int,saveToHistory:bool=False):
self.insert('clipboard',layerNr,saveToHistory)
def insert( self,
image:(str,numpy.ndarray,bytes),
layerNr:int,
saveToHistory:bool=False):
deb=False
# Check if order arguments is correct
if type(layerNr)!=int:
raise Exception("LayerOps.insert got wrong argument type.")
fromClipboard:bool=False
if type(image) is str:
if image == "clipboard":
fromClipboard = True
image=self.clipboardData["Raw"]
# Check if user is in bounds
if layerNr > self.count(): layerNr=self.count()
if layerNr < 0: raise Exception("LayerOps.insert got negative layerNr.")
# Convert image so we finally have a RLE byte array to process
if type(image) is str:
im = cv2.imread(image,cv2.IMREAD_UNCHANGED)
self.insert(im,layerNr,saveToHistory)
return
if isinstance(image,numpy.ndarray): # numpy or cv2 image
# if RGB retrieve Red channel
if image.ndim==3:
image=image[:,:,0]
# Check if correct size
if image.shape != (2560,1440) or image.dtype!=numpy.uint8: # Numpy Array dimensions are switched from PIL.Image dimensions
raise Exception(f"LayerOps.insert needs an CV2 Image with dimensions of 1440x2560 and 8 bit. Got {image.shape[0]}x{image.shape[1]}x{24 if image.ndim==3 else 8} ({image.dtype})")
npArray_1D_uint8=image.flatten()#.astype(numpy.uint8)
rleBytearray=RLE.encode8bImage2RLE(npArray_1D_uint8)
self.insert(rleBytearray,layerNr,saveToHistory)
return
# Here we are inserting RLE
if isinstance(image,bytes):
if fromClipboard and self.clipboardDef==None:
raise Exception("LayerOps.insert got empty clipboard!")
# Check if layerNr in range, could occur on undo after deleting last layer
# print(layerNr, "/", self. self.Layers.count())
insertLast=False
nLayers=len(self.photonfile.LayerDefs)
if layerNr>nLayers: layerNr=nLayers
if layerNr == nLayers:
layerNr=layerNr-1 # temporary reduce layerNr
insertLast=True
if deb:
print ("Start:")
print (" Insert new layer at Nr : ",layerNr)
print (" Append (insertLast) : ",insertLast)
print (" Layer Count : ",self.count())
print (" Header: Layer Defs (addr): ",bytes_to_int(self.photonfile.Header["Layer Defs (addr)"]))
if self.count()>0:
print (" LayerDef(0): Data (addr) : ",bytes_to_int(self.photonfile.LayerDefs[0]["Image Address"]))
# Check deltaHeight
deltaHeight = self.photonfile.layers.height(layerNr)
# Make duplicate of layerDef and layerData if not pasting from clipboard
if fromClipboard == False:
if self.count()>0:
self.clipboardDef=self.__realDeepCopy(self.photonfile.LayerDefs[layerNr])
self.clipboardDef["Data Length"]=int_to_bytes(len(image))
self.clipboardData=self.__realDeepCopy(self.photonfile.LayerData[layerNr])
self.clipboardData["Raw"]=image
else:
# The exposure time and off times are ignored by Photon printer, layerheight not and is cumulative
self.clipboardDef={}
self.clipboardDef["Layer height (mm)"]= self.photonfile.Header["Layer height (mm)"]
self.clipboardDef["Exp. time (s)"] = self.photonfile.Header["Exp. time (s)"]
self.clipboardDef["Off time (s)"] = self.photonfile.Header["Off time (s)"]
self.clipboardDef["Image Address"] = 4 * b'\x00'
self.clipboardDef["Data Length"] = int_to_bytes(len(image))
self.clipboardDef["padding tail"] = pfStruct_LayerDef [5][1]*b'\x00'
self.clipboardData={}
self.clipboardData["Raw"] = image
self.clipboardData["padding tail"] = pfStruct_LayerData [1][1]*b'\x00'
if deb: self.printClipboard()
# Set layerheight correctly
if deb: print ("layerNr",layerNr)
if layerNr==-1: # no other layer to base layer height on so we start on height = 0
self.clipboardDef["Layer height (mm)"] = float_to_bytes(0)
elif layerNr==0: # if first layer than the height should start at 0
self.clipboardDef["Layer height (mm)"] = float_to_bytes(0)
else: # start at layer height of layer at which we insert
curLayerHeight = bytes_to_float(self.photonfile.LayerDefs[layerNr]["Layer height (mm)"])
self.clipboardDef["Layer height (mm)"]=float_to_bytes(curLayerHeight)
# Calc length of new def
defLength=0
for key,val in self.clipboardDef.items():
defLength=defLength+len(val)
if deb:print ("defLength :",defLength)
if deb:print ("taillength:",len(self.photonfile.LayerDefs_padding_tail))
# Set start addresses of layer in clipboard, we add 1 layer(def) so add 36 bytes
if layerNr==-1:
lA=(bytes_to_int(self.photonfile.Header["Layer Defs (addr)"])+
defLength+
len(self.photonfile.LayerDefs_padding_tail)
)
else:
lA=bytes_to_int(self.photonfile.LayerDefs[layerNr]["Image Address"])+defLength
# if lastlayer we need to add last image length
if insertLast: lA=lA+bytes_to_int(self.LayerDefs[layerNr]["Data Length"])
# Starts at 55220 with image size of 33071
if deb:print ("New Image Address (lA):",lA)
self.clipboardDef["Image Address"]=int_to_bytes(lA)
# If we inserting last layer, we correct layerNr
if insertLast: layerNr = layerNr + 1 # fix temporary reduced layerNr
if deb:print ("Correct layerNr because last:",layerNr)
# Shift start addresses of RawData in all LayerDefs due to extra layerdef (36 bytes)
if deb:print("Shift image addresses in layerdefs due to new layerdef:")
for rLayerNr in range(0,nLayers):
curAddr=bytes_to_int(self.LayerDefs[rLayerNr]["Image Address"])
newAddr=curAddr+defLength # size of layerdef
self.LayerDefs[rLayerNr]["Image Address"]= int_to_bytes(newAddr)
if deb:print (" layerdef",rLayerNr,"from",curAddr,"to",newAddr)
# Shift start addresses of RawData in second part of LayerDefs due to extra layerdata
if deb:print("Shift image addresses in layerdefs due to new image data:")
deltaLayerImgAddress = bytes_to_int(self.clipboardDef["Data Length"]) #+ defLength
for rLayerNr in range(layerNr,nLayers):
# Adjust image address for removal of image raw data and end byte
curAddr=bytes_to_int(self.LayerDefs[rLayerNr]["Image Address"])
newAddr=curAddr+deltaLayerImgAddress
self.photonfile.LayerDefs[rLayerNr]["Image Address"]= int_to_bytes(newAddr)
# Adjust layer starting height for removal of layer
curHeight=bytes_to_float(self.LayerDefs[rLayerNr]["Layer height (mm)"])
newHeight=curHeight+deltaHeight
self.photonfile.LayerDefs[rLayerNr]["Layer height (mm)"] = float_to_bytes(newHeight)
#print ("layer, cur, new: ",rLayerNr,curAddr,newAddr, "|", curHeight,newHeight ,">",self.bytes_to_float(self.LayerDefs[rLayerNr]["Layer height (mm)"]))
if deb:print (" layerdef",rLayerNr,"from",curAddr,"to",newAddr)
# Insert layer settings and data and reduce number of layers in header
if layerNr<nLayers:
self.photonfile.LayerDefs.insert(layerNr,self.clipboardDef)
self.photonfile.LayerData.insert(layerNr,self.clipboardData)
else:
self.photonfile.LayerDefs.append(self.clipboardDef)
self.photonfile.LayerData.append(self.clipboardData)
self.photonfile.Header[nrLayersString]=int_to_bytes(len(self.photonfile.LayerDefs))
# Make new copy so second paste will not reference this inserted objects
self.clipboardDef = None #self.photonfile.LayerDefs[layerNr].copy()
self.clipboardData = None #self.photonfile.LayerData[layerNr].copy()
# Debug photonfile
if deb:
print ("Header: Layer Defs (addr):",bytes_to_int(self.photonfile.Header["Layer Defs (addr)"]))
for layerNr in range(self.count()):
self.print(layerNr)