Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Microsoft.ML.sln
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.ML.LightGBM", "sr
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.ML.Ensemble", "src\Microsoft.ML.Ensemble\Microsoft.ML.Ensemble.csproj", "{DCF46B79-1FDB-4DBA-A263-D3D64E3AAA27}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.ML.ImageAnalytics", "src\Microsoft.ML.ImageAnalytics\Microsoft.ML.ImageAnalytics.csproj", "{80FBE6ED-F29B-4FDC-A2A7-137A5577DD00}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -198,6 +200,10 @@ Global
{DCF46B79-1FDB-4DBA-A263-D3D64E3AAA27}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DCF46B79-1FDB-4DBA-A263-D3D64E3AAA27}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DCF46B79-1FDB-4DBA-A263-D3D64E3AAA27}.Release|Any CPU.Build.0 = Release|Any CPU
{80FBE6ED-F29B-4FDC-A2A7-137A5577DD00}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{80FBE6ED-F29B-4FDC-A2A7-137A5577DD00}.Debug|Any CPU.Build.0 = Debug|Any CPU
{80FBE6ED-F29B-4FDC-A2A7-137A5577DD00}.Release|Any CPU.ActiveCfg = Release|Any CPU
{80FBE6ED-F29B-4FDC-A2A7-137A5577DD00}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -234,6 +240,7 @@ Global
{3DEB504D-7A07-48CE-91A2-8047461CB3D4} = {AED9C836-31E3-4F3F-8ABC-929555D3F3C4}
{001F3B4E-FBE4-4001-AFD2-A6A989CD1C25} = {09EADF06-BE25-4228-AB53-95AE3E15B530}
{DCF46B79-1FDB-4DBA-A263-D3D64E3AAA27} = {09EADF06-BE25-4228-AB53-95AE3E15B530}
{80FBE6ED-F29B-4FDC-A2A7-137A5577DD00} = {09EADF06-BE25-4228-AB53-95AE3E15B530}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {41165AF1-35BB-4832-A189-73060F82B01D}
Expand Down
171 changes: 171 additions & 0 deletions src/Microsoft.ML.ImageAnalytics/ImageGrayscaleTransform.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using Microsoft.ML.Runtime;
using Microsoft.ML.Runtime.CommandLine;
using Microsoft.ML.Runtime.Data;
using Microsoft.ML.Runtime.EntryPoints;
using Microsoft.ML.Runtime.Internal.Utilities;
using Microsoft.ML.Runtime.Model;
using Microsoft.ML.Runtime.ImageAnalytics;

[assembly: LoadableClass(ImageGreyscaleTransform.Summary, typeof(ImageGreyscaleTransform), typeof(ImageGreyscaleTransform.Arguments), typeof(SignatureDataTransform),
ImageGreyscaleTransform.UserName, "ImageGreyscaleTransform", "ImageGreyscale")]

[assembly: LoadableClass(ImageGreyscaleTransform.Summary, typeof(ImageGreyscaleTransform), null, typeof(SignatureLoadDataTransform),
ImageGreyscaleTransform.UserName, ImageGreyscaleTransform.LoaderSignature)]

namespace Microsoft.ML.Runtime.Data
{
// REVIEW: Rewrite as LambdaTransform to simplify.
public sealed class ImageGreyscaleTransform : OneToOneTransformBase
{

public sealed class Column : OneToOneColumn
{
public static Column Parse(string str)
{
var res = new Column();
if (res.TryParse(str))
return res;
return null;
}

public bool TryUnparse(StringBuilder sb)
{
Contracts.AssertValue(sb);
return TryUnparseCore(sb);
}

}

public class Arguments : TransformInputBase
{
[Argument(ArgumentType.Multiple | ArgumentType.Required, HelpText = "New column definition(s) (optional form: name:src)", ShortName = "col", SortOrder = 1)]
public Column[] Column;
}

internal const string Summary = "Convert image into grayscale.";

internal const string UserName = "Image Greyscale Transform";
public const string LoaderSignature = "ImageGreyscaleTransform";
private static VersionInfo GetVersionInfo()
{
return new VersionInfo(
modelSignature: "IMGGREY ",

@TomFinley TomFinley Jul 25, 2018

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMGGREY [](start = 33, length = 8)

You had a signature of IMGLOADT for that. Why is this not IMGGREYT?

Also: is it intentional that this be GREY? Elsewhere we are using "gray."

If models already exist with this signature I guess we have to keep it, not sure if that's the case though since you didn't bump the version. :) (I'm not suggesting you bump the version to be clear.) #Closed

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

English are so confusing, grey and gray is apparent to have same meaning, but my brain apparently throw coin during typing and at some point I had code with both spelling all across code. Which I tried to unified, but this one slip from my attention.
This is a new transform which we never had before, and I add it "just in case", and "maybe it will prove useful". So i think it make sense to start from version 1.


In reply to: 205265843 [](ancestors = 205265843)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh sure @Ivanidzo4ka grey and gray are synonymous, though elsewhere you use gray. Also my impression is that we generally favor American spellings (gray) of words vs. British ones (grey).

...Even though I was brought up to use "grey," and had to correct myself since later in my life people thought I was weird. So now I hypercorrect, and you reap the benefits. :D


In reply to: 205597316 [](ancestors = 205597316,205265843)

verWrittenCur: 0x00010001, // Initial
verReadableCur: 0x00010001,
verWeCanReadBack: 0x00010001,
loaderSignature: LoaderSignature);
}

private const string RegistrationName = "ImageGreyscale";

/// <summary>
/// Public constructor corresponding to SignatureDataTransform.

@TomFinley TomFinley Jul 25, 2018

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/// [](start = 8, length = 4)

Did you mean this to be // and not /// , since it is not really terribly sensible for callers? #Closed

/// </summary>

@sfilipi sfilipi Jul 16, 2018

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know we use this allover, and it's plenty meaningful as a code comment, but it will appear in the docs site as well, where might confuse users. Maybe turn it into a code comment removing the triple ///, and

.
Ideally add a meaningful line for the actual documentation. #Resolved

public ImageGreyscaleTransform(IHostEnvironment env, Arguments args, IDataView input)
: base(env, RegistrationName, env.CheckRef(args, nameof(args)).Column, input, t => t is ImageType ? null : "Expected Image type")
{
Host.AssertNonEmpty(Infos);
Host.Assert(Infos.Length == Utils.Size(args.Column));
Metadata.Seal();
}

private ImageGreyscaleTransform(IHost host, ModelLoadContext ctx, IDataView input)
: base(host, ctx, input, t => t is ImageType ? null : "Expected Image type")
{
Host.AssertValue(ctx);
// *** Binary format ***
// <base>
Host.AssertNonEmpty(Infos);
Metadata.Seal();
}

public static ImageGreyscaleTransform Create(IHostEnvironment env, ModelLoadContext ctx, IDataView input)
{
Contracts.CheckValue(env, nameof(env));
var h = env.Register(RegistrationName);
h.CheckValue(ctx, nameof(ctx));
h.CheckValue(input, nameof(input));
ctx.CheckAtModel(GetVersionInfo());
return h.Apply("Loading Model", ch => new ImageGreyscaleTransform(h, ctx, input));
}

public override void Save(ModelSaveContext ctx)
{
Host.CheckValue(ctx, nameof(ctx));
ctx.CheckAtModel();
ctx.SetVersionInfo(GetVersionInfo());

// *** Binary format ***
// <base>
SaveBase(ctx);
}

protected override ColumnType GetColumnTypeCore(int iinfo)
{
Host.Assert(0 <= iinfo & iinfo < Infos.Length);
return Infos[iinfo].TypeSrc;
}

public ColorMatrix GreyscaleColorMatrix = new ColorMatrix(

@TomFinley TomFinley Jul 25, 2018

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

public ColorMatrix GreyscaleColorMatrix [](start = 8, length = 39)

This is a mutable, public instance level field that affects the functionality of the transform.

Probably want this to be private (or at least internal if somehow it is referenced somewhere else), static, and almost certainly readonly. #Closed

new float[][]
{
new float[] {.3f, .3f, .3f, 0, 0},
new float[] {.59f, .59f, .59f, 0, 0},
new float[] {.11f, .11f, .11f, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}
});

protected override Delegate GetGetterCore(IChannel ch, IRow input, int iinfo, out Action disposer)
{
Host.AssertValue(ch, "ch");
Host.AssertValue(input);
Host.Assert(0 <= iinfo && iinfo < Infos.Length);

var src = default(Bitmap);
var getSrc = GetSrcGetter<Bitmap>(input, iinfo);

disposer =
() =>
{
if (src != null)
{
src.Dispose();
src = null;
}
};

ValueGetter<Bitmap> del =
(ref Bitmap dst) =>
{
if (dst != null)
dst.Dispose();

getSrc(ref src);
if (src == null || src.Height <= 0 || src.Width <= 0)
return;

dst = new Bitmap(src.Width, src.Height);
dst.SetResolution(src.VerticalResolution, src.VerticalResolution);
ImageAttributes attributes = new ImageAttributes();
attributes.SetColorMatrix(GreyscaleColorMatrix);
var srcRectangle = new Rectangle(0, 0, src.Width, src.Height);
using (var g = Graphics.FromImage(dst))
{
g.DrawImage(src, srcRectangle, 0, 0, src.Width, src.Height, GraphicsUnit.Pixel, attributes);
}
Host.Assert(dst.Width == src.Width && dst.Height == src.Height);
};

return del;
}
}
}
176 changes: 176 additions & 0 deletions src/Microsoft.ML.ImageAnalytics/ImageLoaderTransform.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Drawing;
using System.IO;
using System.Text;
using Microsoft.ML.Runtime.ImageAnalytics;
using Microsoft.ML.Runtime;
using Microsoft.ML.Runtime.CommandLine;
using Microsoft.ML.Runtime.Data;
using Microsoft.ML.Runtime.EntryPoints;
using Microsoft.ML.Runtime.Internal.Utilities;
using Microsoft.ML.Runtime.Model;

[assembly: LoadableClass(ImageLoaderTransform.Summary, typeof(ImageLoaderTransform), typeof(ImageLoaderTransform.Arguments), typeof(SignatureDataTransform),
ImageLoaderTransform.UserName, "ImageLoaderTransform", "ImageLoader")]

[assembly: LoadableClass(ImageLoaderTransform.Summary, typeof(ImageLoaderTransform), null, typeof(SignatureLoadDataTransform),
ImageLoaderTransform.UserName, ImageLoaderTransform.LoaderSignature)]

namespace Microsoft.ML.Runtime.Data
{
// REVIEW: Rewrite as LambdaTransform to simplify.
public sealed class ImageLoaderTransform : OneToOneTransformBase

@sfilipi sfilipi Jul 16, 2018

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ImageLoaderTransform [](start = 24, length = 20)

summary #Resolved

{
public sealed class Column : OneToOneColumn
{
public static Column Parse(string str)
{
Contracts.AssertNonEmpty(str);

var res = new Column();
if (res.TryParse(str))
return res;
return null;
}

public bool TryUnparse(StringBuilder sb)
{
Contracts.AssertValue(sb);
return TryUnparseCore(sb);
}
}

public sealed class Arguments : TransformInputBase
{
[Argument(ArgumentType.Multiple | ArgumentType.Required, HelpText = "New column definition(s) (optional form: name:src)",
ShortName = "col", SortOrder = 1)]
public Column[] Column;

[Argument(ArgumentType.AtMostOnce, HelpText = "Image folder", ShortName = "folder")]
public string ImageFolder;
}

internal const string Summary = "Loads an image from a file.";
internal const string UserName = "Image Loader Transform";
public const string LoaderSignature = "ImageLoaderTransform";

private static VersionInfo GetVersionInfo()
{
return new VersionInfo(
modelSignature: "IMGLOADT",
verWrittenCur: 0x00010001, // Initial
verReadableCur: 0x00010001,
verWeCanReadBack: 0x00010001,
loaderSignature: LoaderSignature);
}

private readonly ImageType _type;
private string _imageFolder;

private const string RegistrationName = "ImageLoader";

/// <summary>
/// Public constructor corresponding to SignatureDataTransform.
/// </summary>
public ImageLoaderTransform(IHostEnvironment env, Arguments args, IDataView input)
: base(env, RegistrationName, env.CheckRef(args, nameof(args)).Column, input, TestIsText)
{
Host.AssertNonEmpty(Infos);
_imageFolder = args.ImageFolder;
Host.Assert(Infos.Length == Utils.Size(args.Column));
_type = new ImageType();
Metadata.Seal();
}

private ImageLoaderTransform(IHost host, ModelLoadContext ctx, IDataView input)
: base(host, ctx, input, TestIsText)
{
Host.AssertValue(ctx);

// *** Binary format ***
// <base>
_imageFolder = ctx.Reader.ReadString();
_type = new ImageType();
Metadata.Seal();
}

public static ImageLoaderTransform Create(IHostEnvironment env, ModelLoadContext ctx, IDataView input)
{
Contracts.CheckValue(env, nameof(env));
var h = env.Register(RegistrationName);
h.CheckValue(ctx, nameof(ctx));
h.CheckValue(input, nameof(input));
ctx.CheckAtModel(GetVersionInfo());
return h.Apply("Loading Model", ch => new ImageLoaderTransform(h, ctx, input));
}

public override void Save(ModelSaveContext ctx)
{
Host.CheckValue(ctx, nameof(ctx));
ctx.CheckAtModel();
ctx.SetVersionInfo(GetVersionInfo());

// *** Binary format ***
// <base>
ctx.Writer.Write(_imageFolder);
SaveBase(ctx);
}

protected override ColumnType GetColumnTypeCore(int iinfo)
{
Host.Check(0 <= iinfo && iinfo < Infos.Length);
return _type;
}

protected override Delegate GetGetterCore(IChannel ch, IRow input, int iinfo, out Action disposer)
{
Host.AssertValueOrNull(ch);
Host.AssertValue(input);
Host.Assert(0 <= iinfo && iinfo < Infos.Length);
disposer = null;

var getSrc = GetSrcGetter<DvText>(input, iinfo);
DvText src = default(DvText);
ValueGetter<Bitmap> del =
(ref Bitmap dst) =>
{
if (dst != null)
{
dst.Dispose();
dst = null;
}

getSrc(ref src);

if (src.Length > 0)
{
// Catch exceptions and pass null through. Should also log failures...
try
{
string path = src.ToString();
if (!string.IsNullOrWhiteSpace(_imageFolder))
path = Path.Combine(_imageFolder, path);
dst = new Bitmap(filename: path, useIcm: false);
}
catch (Exception e)
{
// REVIEW: We catch everything since the documentation for new Bitmap(string)
// appears to be incorrect. When the file isn't found, it throws an ArgumentException,
// while the documentation says FileNotFoundException. Not sure what it will throw
// in other cases, like corrupted file, etc.

// REVIEW : Log failures.
ch.Info(e.Message);
ch.Info(e.StackTrace);
dst = null;
}
}
};
return del;
}
}
}
Loading