dotnet / dotnet/machinelearning

[Feature] transform image rotation

Open
#5,734 0 comments 0 reactions 0 assignees View on GitHub
area-Vision enhancement Priority:2
Dominant language
C#
Stars
9.4k
Forks
2k
Avg merge
2d 20h
Merged PRs (30d)
11

Description

Should be possible implement something like it (at the moment we have only resize for image manipulation):

mlContext.Transforms.RotateImage(outputColumnName: "ImgRotated", inputColumnName: "ImagePath", angle:"Angle", targetWidth:"Width", targetHeight:"Height")

that use a function like this (rotate on center and crop image)
```
public static Bitmap GetRotatedByteArrayToBitmap(byte[] bytes, float angle, int targetWidth, int targetHeight)
{
using var ms = new MemoryStream(bytes);
var bm = new Bitmap(ms);

// Make a Matrix to represent rotation by this angle.
using var rotateAtOrigin = new Matrix();
rotateAtOrigin.Rotate(angle);

// Rotate the image's corners to see how big
// it will be after rotation.
PointF[] points =
{
new PointF(0, 0),
new PointF(bm.Width, 0),
new PointF(bm.Width, bm.Height),
new PointF(0, bm.Height)
};

rotateAtOrigin.TransformPoints(points);
GetPointBounds(points, out var xmin, out var xmax, out var ymin, out var ymax);

// Make a bitmap to hold the rotated result.
var wid = (int)Math.Round(xmax - xmin);
var hgt = (int)Math.Round(ymax - ymin);
using var result = new Bitmap(wid, hgt);

// Create the real rotation transformation.
var rotateAtCenter = new Matrix();
rotateAtCenter.RotateAt(angle, new PointF(wid / 2f, hgt / 2f));

// Draw the image onto the new bitmap rotated.
using (var gr = Graphics.FromImage(result))
{
// Use smooth image interpolation.
gr.InterpolationMode = InterpolationMode.High;

// Clear with the color in the image's upper left corner.
gr.Clear(bm.GetPixel(0, 0));

//// For debugging. (Makes it easier to see the background.)
//gr.Clear(Color.LightBlue);

// Set up the transformation to rotate.
gr.Transform = rotateAtCenter;

// Draw the image centered on the bitmap.
var x = (wid - bm.Width) / 2;
var y = (hgt - bm.Height) / 2;
gr.DrawImage(bm, x, y);
}

int xt = result.Width / 2 - targetWidth / 2;
int yt = result.Height / 2 - targetHeight / 2;

Rectangle cloneRect = new Rectangle(xt, yt, targetWidth, targetHeight);
return result.Clone(cloneRect, result.PixelFormat);
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.