Skip to content

Commit e823735

Browse files
author
Ryan Lai
authored
Update Squeezenet c++ and C# sample to be explicit with colorspace management of GetSoftwareBitmapAsync (#282)
* Updated squeezenet cpp sample to be explicit about managing color space * Updated squeezenet c# sample to be explicit about managing color space * Case insensitive value when looking up metadata * PR comments to make try catch tighter
1 parent 8ca3e52 commit e823735

File tree

2 files changed

+119
-17
lines changed

2 files changed

+119
-17
lines changed

Samples/SqueezeNetObjectDetection/Desktop/cpp/main.cpp

Lines changed: 64 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,10 @@ hstring imagePath;
2222
// helper functions
2323
string GetModulePath();
2424
void LoadLabels();
25-
VideoFrame LoadImageFile(hstring filePath);
25+
VideoFrame LoadImageFile(hstring filePath, ColorManagementMode colorManagementMode);
2626
void PrintResults(IVectorView<float> results);
2727
bool ParseArgs(int argc, char* argv[]);
28+
ColorManagementMode GetColorManagementMode(const LearningModel& model);
2829

2930
wstring GetModelPath()
3031
{
@@ -57,9 +58,13 @@ int main(int argc, char* argv[])
5758
ticks = GetTickCount() - ticks;
5859
printf("model file loaded in %d ticks\n", ticks);
5960

61+
// get model color management mode
62+
printf("Getting model color management mode...\n");
63+
ColorManagementMode colorManagementMode = GetColorManagementMode(model);
64+
6065
// load the image
6166
printf("Loading the image...\n");
62-
auto imageFrame = LoadImageFile(imagePath);
67+
auto imageFrame = LoadImageFile(imagePath, colorManagementMode);
6368
// now create a session and binding
6469
LearningModelSession session(model, LearningModelDevice(deviceKind));
6570
LearningModelBinding binding(session);
@@ -153,28 +158,76 @@ void LoadLabels()
153158
}
154159
}
155160

156-
VideoFrame LoadImageFile(hstring filePath)
161+
ColorManagementMode GetColorManagementMode(const LearningModel& model)
162+
{
163+
// Get model color space gamma
164+
hstring gammaSpace = L"";
165+
try
166+
{
167+
gammaSpace = model.Metadata().Lookup(L"Image.ColorSpaceGamma");
168+
}
169+
catch (...)
170+
{
171+
printf(" Model does not have color space gamma information. Will color manage to sRGB by default...\n");
172+
}
173+
if (gammaSpace == L"" || _wcsicmp(gammaSpace.c_str(), L"SRGB") == 0)
174+
{
175+
return ColorManagementMode::ColorManageToSRgb;
176+
}
177+
// Due diligence should be done to make sure that the input image is within the model's colorspace. There are multiple non-sRGB color spaces.
178+
printf(" Model metadata indicates that color gamma space is : %ws. Will not manage color space to sRGB...\n", gammaSpace.c_str());
179+
return ColorManagementMode::DoNotColorManage;
180+
}
181+
182+
VideoFrame LoadImageFile(hstring filePath, ColorManagementMode colorManagementMode)
157183
{
184+
BitmapDecoder decoder = NULL;
158185
try
159186
{
160187
// open the file
161188
StorageFile file = StorageFile::GetFileFromPathAsync(filePath).get();
162189
// get a stream on it
163190
auto stream = file.OpenAsync(FileAccessMode::Read).get();
164191
// Create the decoder from the stream
165-
BitmapDecoder decoder = BitmapDecoder::CreateAsync(stream).get();
166-
// get the bitmap
167-
SoftwareBitmap softwareBitmap = decoder.GetSoftwareBitmapAsync().get();
168-
// load a videoframe from it
169-
VideoFrame inputImage = VideoFrame::CreateWithSoftwareBitmap(softwareBitmap);
170-
// all done
171-
return inputImage;
192+
decoder = BitmapDecoder::CreateAsync(stream).get();
172193
}
173194
catch (...)
174195
{
175-
printf("failed to load the image file, make sure you are using fully qualified paths\r\n");
196+
printf(" Failed to load the image file, make sure you are using fully qualified paths\r\n");
176197
exit(EXIT_FAILURE);
177198
}
199+
SoftwareBitmap softwareBitmap = NULL;
200+
try
201+
{
202+
softwareBitmap = decoder.GetSoftwareBitmapAsync(
203+
decoder.BitmapPixelFormat(),
204+
decoder.BitmapAlphaMode(),
205+
BitmapTransform(),
206+
ExifOrientationMode::RespectExifOrientation,
207+
colorManagementMode
208+
).get();
209+
}
210+
catch (hresult_error hr)
211+
{
212+
printf(" Failed to create SoftwareBitmap! Please make sure that input image is within the model's colorspace.\n");
213+
printf(" %ws\n", hr.message().c_str());
214+
exit(hr.code());
215+
}
216+
VideoFrame inputImage = NULL;
217+
try
218+
{
219+
// load a videoframe from it
220+
inputImage = VideoFrame::CreateWithSoftwareBitmap(softwareBitmap);
221+
}
222+
catch (hresult_error hr)
223+
{
224+
printf("Failed to create videoframe from software bitmap.");
225+
printf(" %ws\n", hr.message().c_str());
226+
exit(hr.code());
227+
}
228+
// all done
229+
return inputImage;
230+
178231
}
179232

180233
void PrintResults(IVectorView<float> results)

Samples/SqueezeNetObjectDetection/NETCore/cs/Program.cs

Lines changed: 55 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,11 @@ static int Main(string[] args)
4545
// Create the evaluation session with the model and device
4646
_session = new LearningModelSession(_model, new LearningModelDevice(_deviceKind));
4747

48+
Console.WriteLine("Getting color management mode...");
49+
ColorManagementMode colorManagementMode = GetColorManagementMode();
50+
4851
Console.WriteLine("Loading the image...");
49-
ImageFeatureValue imageTensor = LoadImageFile();
52+
ImageFeatureValue imageTensor = LoadImageFile(colorManagementMode);
5053

5154
// create a binding object from the session
5255
Console.WriteLine("Binding...");
@@ -117,17 +120,63 @@ private static T AsyncHelper<T> (IAsyncOperation<T> operation)
117120
return operation.GetResults();
118121
}
119122

120-
private static ImageFeatureValue LoadImageFile()
123+
private static ImageFeatureValue LoadImageFile(ColorManagementMode colorManagementMode)
121124
{
122-
StorageFile imageFile = AsyncHelper(StorageFile.GetFileFromPathAsync(_imagePath));
123-
IRandomAccessStream stream = AsyncHelper(imageFile.OpenReadAsync());
124-
BitmapDecoder decoder = AsyncHelper(BitmapDecoder.CreateAsync(stream));
125-
SoftwareBitmap softwareBitmap = AsyncHelper(decoder.GetSoftwareBitmapAsync());
125+
BitmapDecoder decoder = null;
126+
try
127+
{
128+
StorageFile imageFile = AsyncHelper(StorageFile.GetFileFromPathAsync(_imagePath));
129+
IRandomAccessStream stream = AsyncHelper(imageFile.OpenReadAsync());
130+
decoder = AsyncHelper(BitmapDecoder.CreateAsync(stream));
131+
}
132+
catch (Exception e)
133+
{
134+
Console.WriteLine("Failed to load image file! Make sure that fully qualified paths are used.");
135+
Console.WriteLine(" Exception caught.\n {0}", e);
136+
System.Environment.Exit(e.HResult);
137+
}
138+
SoftwareBitmap softwareBitmap = null;
139+
try
140+
{
141+
softwareBitmap = AsyncHelper(
142+
decoder.GetSoftwareBitmapAsync(
143+
decoder.BitmapPixelFormat,
144+
decoder.BitmapAlphaMode,
145+
new BitmapTransform(),
146+
ExifOrientationMode.RespectExifOrientation,
147+
colorManagementMode
148+
)
149+
);
150+
}
151+
catch (Exception e)
152+
{
153+
Console.WriteLine("Failed to create SoftwareBitmap! Please make sure that input image is within the model's colorspace.");
154+
Console.WriteLine(" Exception caught.\n {0}", e);
155+
System.Environment.Exit(e.HResult);
156+
}
126157
softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
127158
VideoFrame inputImage = VideoFrame.CreateWithSoftwareBitmap(softwareBitmap);
128159
return ImageFeatureValue.CreateFromVideoFrame(inputImage);
129160
}
130161

162+
private static ColorManagementMode GetColorManagementMode()
163+
{
164+
// Get model color space gamma
165+
string gammaSpace = "";
166+
bool doesModelContainGammaSpaceMetadata = _model.Metadata.TryGetValue("Image.ColorSpaceGamma", out gammaSpace);
167+
if (!doesModelContainGammaSpaceMetadata)
168+
{
169+
Console.WriteLine(" Model does not have color space gamma information. Will color manage to sRGB by default...");
170+
}
171+
if (!doesModelContainGammaSpaceMetadata || gammaSpace.Equals("SRGB", StringComparison.CurrentCultureIgnoreCase))
172+
{
173+
return ColorManagementMode.ColorManageToSRgb;
174+
}
175+
// Due diligence should be done to make sure that the input image is within the model's colorspace. There are multiple non-sRGB color spaces.
176+
Console.WriteLine(" Model metadata indicates that color gamma space is : {0}. Will not manage color space to sRGB...", gammaSpace);
177+
return ColorManagementMode.DoNotColorManage;
178+
}
179+
131180
private static void PrintResults(IReadOnlyList<float> resultVector)
132181
{
133182
// load the labels

0 commit comments

Comments
 (0)