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
|
/*
* GNU AFFERO GENERAL PUBLIC LICENSE
* Version 3, 19 November 2007
* Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
* Everyone is permitted to copy and distribute verbatim copies
* of this license document, but changing it is not allowed.
*/
using Emgu.CV;
using Emgu.CV.CvEnum;
using System;
using System.ComponentModel;
using System.IO;
using System.Threading.Tasks;
using UVtools.Core.EmguCV;
using UVtools.Core.Extensions;
using UVtools.Core.FileFormats;
namespace UVtools.Core.Operations;
[Serializable]
public sealed class OperationLayerExportImage : Operation
{
#region Enums
public enum LayerExportImageTypes : byte
{
[Description("PNG: Portable Network Graphics")]
PNG,
[Description("JPG: Joint Photographic Experts Group")]
JPG,
[Description("JPEG: Joint Photographic Experts Group")]
JPEG,
[Description("JP2: Joint Photographic Experts Group (JPEG 2000)")]
JP2,
[Description("TIF: Tag Image File Format")]
TIF,
[Description("TIFF: Tag Image File Format")]
TIFF,
[Description("BMP: Bitmap")]
BMP,
[Description("PBM: Portable Bitmap")]
PBM,
[Description("PGM: Portable Greymap")]
PGM,
//[Description("PPM: Portable Pixmap")]
//PPM,
[Description("SR: Sun raster")]
SR,
[Description("RAS: Sun raster")]
RAS,
[Description("SVG: Scalable Vector Graphics")]
SVG
}
#endregion
#region Members
private string _outputFolder = null!;
private string _filename = "layer";
private LayerExportImageTypes _imageType = LayerExportImageTypes.PNG;
private RotateDirection _rotateDirection = RotateDirection.None;
private FlipDirection _flipDirection = FlipDirection.None;
private bool _padLayerIndex = true;
private bool _cropByRoi = true;
#endregion
#region Overrides
public override bool CanHaveProfiles => false;
public override string IconClass => "fas fa-file-image";
public override string Title => "Export layers to images";
public override string Description =>
"Export a layer range to images.";
public override string ConfirmationText =>
$"export {_imageType} images from layers {LayerIndexStart} through {LayerIndexEnd}?";
public override string ProgressTitle =>
$"Exporting {_imageType} images from layers {LayerIndexStart} through {LayerIndexEnd}";
public override string ProgressAction => $"Exported {_imageType} images";
/*public override string ValidateInternally()
{
var sb = new StringBuilder();
if (LayerRangeCount < 2)
{
sb.AppendLine("To generate a heat map at least two layers are required.");
}
return sb.ToString();
}*/
public override string ToString()
{
var result = $"[Crop by ROI: {_cropByRoi}] [Pad index: {_padLayerIndex}]" +
LayerRangeString;
if (!string.IsNullOrEmpty(ProfileName)) result = $"{ProfileName}: {result}";
return result;
}
#endregion
#region Properties
public string OutputFolder
{
get => _outputFolder;
set => RaiseAndSetIfChanged(ref _outputFolder, value);
}
public string Filename
{
get => _filename;
set => RaiseAndSetIfChanged(ref _filename, value);
}
public LayerExportImageTypes ImageType
{
get => _imageType;
set => RaiseAndSetIfChanged(ref _imageType, value);
}
public RotateDirection RotateDirection
{
get => _rotateDirection;
set => RaiseAndSetIfChanged(ref _rotateDirection, value);
}
public FlipDirection FlipDirection
{
get => _flipDirection;
set => RaiseAndSetIfChanged(ref _flipDirection, value);
}
public bool PadLayerIndex
{
get => _padLayerIndex;
set => RaiseAndSetIfChanged(ref _padLayerIndex, value);
}
public bool CropByROI
{
get => _cropByRoi;
set => RaiseAndSetIfChanged(ref _cropByRoi, value);
}
#endregion
#region Constructor
public OperationLayerExportImage()
{ }
public OperationLayerExportImage(FileFormat slicerFile) : base(slicerFile)
{
_flipDirection = SlicerFile.DisplayMirror;
}
public override void InitWithSlicerFile()
{
_outputFolder = Path.Combine(Path.GetDirectoryName(SlicerFile.FileFullPath) ?? string.Empty, FileFormat.GetFileNameStripExtensions(SlicerFile.FileFullPath) ?? string.Empty);
}
#endregion
#region Methods
protected override bool ExecuteInternally(OperationProgress progress)
{
if (!Directory.Exists(_outputFolder))
{
Directory.CreateDirectory(_outputFolder);
}
var slicedFileNameNoExt = SlicerFile.FilenameNoExt;
Parallel.For(LayerIndexStart, LayerIndexEnd+1, CoreSettings.GetParallelOptions(progress), layerIndex =>
{
using var mat = SlicerFile[layerIndex].LayerMat;
var matRoi = mat;
if (_cropByRoi && HaveROI)
{
matRoi = GetRoiOrDefault(mat);
}
if (_flipDirection != FlipDirection.None)
{
CvInvoke.Flip(matRoi, matRoi, (FlipType)_flipDirection);
}
if (_rotateDirection != RotateDirection.None)
{
CvInvoke.Rotate(matRoi, matRoi, (RotateFlags)_rotateDirection);
}
var filename = SlicerFile[layerIndex].FormatFileName(_filename, _padLayerIndex ? SlicerFile.LayerDigits : byte.MinValue, IndexStartNumber.Zero, string.Empty);
var fileFullPath = Path.Combine(_outputFolder, $"{filename}.{_imageType.ToString().ToLower()}");
if (_imageType != LayerExportImageTypes.SVG)
{
matRoi.Save(fileFullPath);
}
else
{
// SVG
CvInvoke.Threshold(matRoi, matRoi, 127, byte.MaxValue, ThresholdType.Binary); // Remove AA
using var contours = matRoi.FindContours(out var hierarchy, RetrType.Tree);
using TextWriter tw = new StreamWriter(fileFullPath);
tw.WriteLine("<!--");
tw.WriteLine($"# Generated by {About.Software} v{About.VersionStr} {About.SystemBits} @ {DateTime.UtcNow} #");
tw.WriteLine($"File: {SlicerFile.Filename}");
tw.WriteLine($"{SlicerFile[layerIndex].ToString().Replace(", ", "\n")}");
tw.WriteLine("-->");
tw.WriteLine("<svg " +
"xmlns=\"http://www.w3.org/2000/svg\" " +
//"xmlns:xlink=\"http://www.w3.org/1999/xlink\" " +
//"version=\"1.1\" " +
$"id=\"{slicedFileNameNoExt}_{filename}\" " +
$"data-name=\"{slicedFileNameNoExt}_{filename}\" " +
//"x=\"0\" " +
//"y=\"0\" " +
$"width=\"{matRoi.Width}\" " +
$"height=\"{matRoi.Height}\" " +
$"viewBox=\"0 0 {matRoi.Width} {matRoi.Height}\">");
tw.WriteLine("\t<defs>");
tw.WriteLine("\t\t<style>");
//tw.WriteLine("\t\tsvg { background-color: #000000; }");
tw.WriteLine("\t\t.background { fill: #000000; }");
//tw.WriteLine("\t\t.black { fill: #000000; fill-rule: evenodd; }");
//tw.WriteLine("\t\t.white { fill: #FFFFFF; fill-rule: evenodd; }");
tw.WriteLine("\t\tpath { fill: #FFFFFF; fill-rule: evenodd; }");
tw.WriteLine("\t\t</style>");
tw.WriteLine("\t</defs>");
tw.WriteLine($"\t<title>{slicedFileNameNoExt} #{layerIndex}</title>");
tw.WriteLine($"\t<g id=\"layer{layerIndex}\">");
tw.WriteLine($"\t<rect class=\"background\" width=\"{mat.Width}\" height=\"{mat.Height}\"/>");
//
//hierarchy[i][0]: the index of the next contour of the same level
//hierarchy[i][1]: the index of the previous contour of the same level
//hierarchy[i][2]: the index of the first child
//hierarchy[i][3]: the index of the parent
//
bool firstTime = true;
for (int i = 0; i < contours.Size; i++)
{
if (hierarchy[i, EmguContour.HierarchyParent] == -1) // Top hierarchy
{
if (firstTime)
{
firstTime = false;
}
else
{
tw.WriteLine("\"/>");
}
tw.Write("\t<path d=\"");
}
else
{
tw.Write(" ");
}
tw.Write($"M {contours[i][0].X} {contours[i][0].Y} L");
for (int x = 1; x < contours[i].Size; x++)
{
tw.Write($" {contours[i][x].X} {contours[i][x].Y}");
}
tw.Write(" Z");
}
if(!firstTime) tw.WriteLine("\"/>");
// Old method!
/*for (int i = 0; i < contours.Size; i++)
{
if (contours[i].Size == 0) continue;
var style = "white";
int parentIndex = i;
int count = 0;
while ((parentIndex = (int)hierarchyJagged.GetValue(0, parentIndex, 3)) != -1)
{
count++;
}
if (count % 2 != 0)
style = "black";
tw.Write($"\t<path class=\"{style}\" d=\"M{contours[i][0].X} {contours[i][0].Y}");
for (int x = 1; x < contours[i].Size; x++)
{
tw.Write($",L{contours[i][x].X} {contours[i][x].Y}");
}
tw.WriteLine("Z\"/>");
}*/
tw.WriteLine("\t</g>");
tw.WriteLine("</svg>");
}
progress.LockAndIncrement();
});
return !progress.Token.IsCancellationRequested;
}
#endregion
#region Equality
private bool Equals(OperationLayerExportImage other)
{
return _outputFolder == other._outputFolder && _filename == other._filename && _imageType == other._imageType && _rotateDirection == other._rotateDirection && _flipDirection == other._flipDirection && _padLayerIndex == other._padLayerIndex && _cropByRoi == other._cropByRoi;
}
public override bool Equals(object? obj)
{
return ReferenceEquals(this, obj) || obj is OperationLayerExportImage other && Equals(other);
}
public override int GetHashCode()
{
return HashCode.Combine(_outputFolder, _filename, (int) _imageType, (int) _rotateDirection, (int) _flipDirection, _padLayerIndex, _cropByRoi);
}
#endregion
}
|