forked from microsoft/Windows-Machine-Learning
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImageHelper.cs
More file actions
216 lines (192 loc) · 9.45 KB
/
ImageHelper.cs
File metadata and controls
216 lines (192 loc) · 9.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.AI.MachineLearning;
using Windows.Foundation;
using Windows.Graphics.Imaging;
using Windows.Media;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
namespace StyleTransfer
{
public sealed class ImageHelper
{
/// <summary>
/// Crop image given a imageVariableDescription
/// </summary>
/// <param name="inputVideoFrame"></param>
/// <returns></returns>
public static IAsyncOperation<VideoFrame> CenterCropImageAsync(VideoFrame inputVideoFrame, ImageFeatureDescriptor imageVariableDescription)
{
return CenterCropImageAsync(inputVideoFrame, imageVariableDescription.Width, imageVariableDescription.Height);
}
/// <summary>
/// Crop image given a target width and height
/// </summary>
/// <param name="inputVideoFrame"></param>
/// <returns></returns>
public static IAsyncOperation<VideoFrame> CenterCropImageAsync(VideoFrame inputVideoFrame, uint targetWidth, uint targetHeight)
{
return AsyncInfo.Run(async (token) =>
{
bool useDX = inputVideoFrame.SoftwareBitmap == null;
VideoFrame result = null;
// Center crop
try
{
// Since we will be center-cropping the image, figure which dimension has to be clipped
var frameHeight = useDX ? inputVideoFrame.Direct3DSurface.Description.Height : inputVideoFrame.SoftwareBitmap.PixelHeight;
var frameWidth = useDX ? inputVideoFrame.Direct3DSurface.Description.Width : inputVideoFrame.SoftwareBitmap.PixelWidth;
Rect cropRect = GetCropRect(frameWidth, frameHeight, targetWidth, targetHeight);
BitmapBounds cropBounds = new BitmapBounds()
{
Width = (uint)cropRect.Width,
Height = (uint)cropRect.Height,
X = (uint)cropRect.X,
Y = (uint)cropRect.Y
};
// Create the VideoFrame to be bound as input for evaluation
if (useDX)
{
if (inputVideoFrame.Direct3DSurface == null)
{
throw (new Exception("Invalid VideoFrame without SoftwareBitmap nor D3DSurface"));
}
result = new VideoFrame(BitmapPixelFormat.Bgra8,
(int)targetWidth,
(int)targetHeight,
BitmapAlphaMode.Premultiplied);
}
else
{
result = new VideoFrame(BitmapPixelFormat.Bgra8,
(int)targetWidth,
(int)targetHeight,
BitmapAlphaMode.Premultiplied);
}
await inputVideoFrame.CopyToAsync(result, cropBounds, null);
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
return result;
});
}
/// <summary>
/// Calculate the center crop bounds given a set of source and target dimensions
/// </summary>
/// <param name="frameWidth"></param>
/// <param name="frameHeight"></param>
/// <param name="targetWidth"></param>
/// <param name="targetHeight"></param>
/// <returns></returns>
public static Rect GetCropRect(int frameWidth, int frameHeight, uint targetWidth, uint targetHeight)
{
Rect rect = new Rect();
// we need to recalculate the crop bounds in order to correctly center-crop the input image
float flRequiredAspectRatio = (float)targetWidth / targetHeight;
if (flRequiredAspectRatio * frameHeight > (float)frameWidth)
{
// clip on the y axis
rect.Height = (uint)Math.Min((frameWidth / flRequiredAspectRatio + 0.5f), frameHeight);
rect.Width = (uint)frameWidth;
rect.X = 0;
rect.Y = (uint)(frameHeight - rect.Height) / 2;
}
else // clip on the x axis
{
rect.Width = (uint)Math.Min((flRequiredAspectRatio * frameHeight + 0.5f), frameWidth);
rect.Height = (uint)frameHeight;
rect.X = (uint)(frameWidth - rect.Width) / 2; ;
rect.Y = 0;
}
return rect;
}
/// <summary>
/// Launch file picker for user to select a picture file and return a VideoFrame
/// </summary>
/// <returns>VideoFrame instanciated from the selected image file</returns>
public static IAsyncOperation<VideoFrame> LoadVideoFrameFromFilePickedAsync()
{
return AsyncInfo.Run(async (token) =>
{
// Trigger file picker to select an image file
FileOpenPicker fileOpenPicker = new FileOpenPicker();
fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
fileOpenPicker.FileTypeFilter.Add(".jpg");
fileOpenPicker.FileTypeFilter.Add(".png");
fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;
StorageFile selectedStorageFile = await fileOpenPicker.PickSingleFileAsync();
if (selectedStorageFile == null)
{
return null;
}
return await LoadVideoFrameFromStorageFileAsync(selectedStorageFile);
});
}
/// <summary>
/// Decode image from a StorageFile and return a VideoFrame
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public static IAsyncOperation<VideoFrame> LoadVideoFrameFromStorageFileAsync(StorageFile file)
{
return AsyncInfo.Run(async (token) =>
{
VideoFrame resultFrame = null;
SoftwareBitmap softwareBitmap;
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
{
// Create the decoder from the stream
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
// Get the SoftwareBitmap representation of the file in BGRA8 format
softwareBitmap = await decoder.GetSoftwareBitmapAsync();
softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
}
// Encapsulate the image in the WinML image type (VideoFrame) to be bound and evaluated
resultFrame = VideoFrame.CreateWithSoftwareBitmap(softwareBitmap);
return resultFrame;
});
}
/// <summary>
/// Launch file picker for user to select a file and save a VideoFrame to it
/// </summary>
/// <param name="frame"></param>
/// <returns></returns>
public static IAsyncAction SaveVideoFrameToFilePickedAsync(VideoFrame frame)
{
return AsyncInfo.Run(async (token) =>
{
// Trigger file picker to select an image file
FileSavePicker fileSavePicker = new FileSavePicker();
fileSavePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
fileSavePicker.FileTypeChoices.Add("image file", new List<string>() { ".jpg" });
fileSavePicker.SuggestedFileName = "NewImage";
StorageFile selectedStorageFile = await fileSavePicker.PickSaveFileAsync();
if (selectedStorageFile == null)
{
return;
}
using (IRandomAccessStream stream = await selectedStorageFile.OpenAsync(FileAccessMode.ReadWrite))
{
VideoFrame frameToEncode = frame;
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
if (frameToEncode.SoftwareBitmap == null)
{
Debug.Assert(frame.Direct3DSurface != null);
frameToEncode = new VideoFrame(BitmapPixelFormat.Bgra8, frame.Direct3DSurface.Description.Width, frame.Direct3DSurface.Description.Height);
await frame.CopyToAsync(frameToEncode);
}
encoder.SetSoftwareBitmap(
frameToEncode.SoftwareBitmap.BitmapPixelFormat.Equals(BitmapPixelFormat.Bgra8) ?
frameToEncode.SoftwareBitmap
: SoftwareBitmap.Convert(frameToEncode.SoftwareBitmap, BitmapPixelFormat.Bgra8));
await encoder.FlushAsync();
}
});
}
}
}