Skip to content

Instantly share code, notes, and snippets.

@qassa
Created January 18, 2018 14:52
Show Gist options
  • Save qassa/4a5259d82e7a874bcb3410caddc95768 to your computer and use it in GitHub Desktop.
Save qassa/4a5259d82e7a874bcb3410caddc95768 to your computer and use it in GitHub Desktop.
Simple difference oriented algorithm for motion detetion in WPF
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
private ImageMatrix create_matrix(string file_name)
{
Uri imageUri = new Uri(file_name, UriKind.Relative);
BitmapImage imageBitmap = new BitmapImage(imageUri);
int height = imageBitmap.PixelHeight;
int width = imageBitmap.PixelWidth;
ImageMatrix res = new ImageMatrix(height, width, file_name);
int nStride = (imageBitmap.PixelWidth * imageBitmap.Format.BitsPerPixel) / 8;
byte[] pixelByteArray = new byte[imageBitmap.PixelHeight * nStride];
imageBitmap.CopyPixels(pixelByteArray, nStride, 0);
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width-4; j++)
{
int z = i * width * 4;
byte alpha = pixelByteArray[z + j*4];
byte red = pixelByteArray[z + (j*4+1)];
byte green = pixelByteArray[z + (j*4+2)];
byte blue = pixelByteArray[z + (j*4+3)];
Color color = Color.FromArgb(alpha, red, green, blue);
res.Matrix[i, j] = (byte)((color.R + color.G + color.B) / 3);
}
}
return res;
}
private void tsmiDifference_Click()
{
ImageMatrix matrix1 = create_matrix("Screenshot-1.jpg");
ImageMatrix matrix2 = create_matrix("Screenshot-2.jpg");
ImageMatrix picture = new ImageMatrix(matrix1.Height, matrix1.Width, "");
for (int i = 0; i < matrix1.Height; i++)
{
for (int j = 0; j < matrix1.Width; j++)
{
byte light1 = matrix1.Matrix[i, j];
byte light2 = matrix2.Matrix[i, j];
byte light = (byte)Math.Abs(light2 - light1);
if (light < 5) light = 0; else light = 255;
picture.Matrix[i, j] = light;
}
}
difference_image.Source = picture.GenerateImageFromMatr();
}
internal class ImageMatrix
{
public int Height;
public int Width;
internal byte[,] Matrix;
string uri;
public ImageMatrix(int height, int width, string uri)
{
Height = height;
Width = width;
this.uri = uri;
this.Matrix = new byte[Height, Width];
}
public WriteableBitmap GenerateImageFromMatr()
{
WriteableBitmap wb = new WriteableBitmap(Width,
Height, 96, 96, PixelFormats.Bgra32, null);
Int32Rect rect = new Int32Rect(0, 0, Width, Height);
byte[] pixels = new byte[Width * Height * wb.Format.BitsPerPixel / 8];
for (int x = 0; x < wb.PixelHeight; x++)
{
for (int y = 0; y < wb.PixelWidth; y++)
{
byte alpha = 255;
byte light = Matrix[x,y];
int pixelOffset = (y + x * wb.PixelWidth) * wb.Format.BitsPerPixel / 8;
pixels[pixelOffset] = light;
pixels[pixelOffset+1] = light;
pixels[pixelOffset+2] = light;
pixels[pixelOffset+3] = alpha;
}
int stride = (wb.PixelWidth * wb.Format.BitsPerPixel) / 8;
wb.WritePixels(rect, pixels, stride, 0);
}
return wb;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment