Skip to content

Instantly share code, notes, and snippets.

@dg1an3
Created October 26, 2018 16:12
Show Gist options
  • Save dg1an3/c25d09c281411440c07a2688b0b896eb to your computer and use it in GitHub Desktop.
Save dg1an3/c25d09c281411440c07a2688b0b896eb to your computer and use it in GitHub Desktop.
csx-based image helpers
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
// width/height helpers
static int Width<TPixel>(this TPixel[,] pixels) => pixels.GetLength(0);
static int Height<TPixel>(this TPixel[,] pixels) => pixels.GetLength(1);
// range helper
static IEnumerable<int> From(int min, int max) => Enumerable.Range(min, max);
// pixel access helper
static TPixel Pixel<TPixel>(this TPixel[,] pixels, int x, int y) =>
pixels[x % pixels.Width(), y % pixels.Height()];
// histogram statistic
static IDictionary<TPixel, int> Histogram<TPixel>(this TPixel[,] pixels) =>
pixels.Cast<TPixel>().GroupBy(px => px).ToDictionary(grp => grp.Key, grp => grp.Count());
// select returns enumerable of pixel values
static IEnumerable<TPixel> Select<TPixel>(this TPixel[,] pixels, Func<int, int, TPixel> func) =>
From(0, pixels.Width()).SelectMany(y => From(0, pixels.Height()).Select(x => func(x, y)));
// transform creates a new image from an existing one and transform func
static TPixel[,] FromFunc<TPixel>(int width, int height, Func<int, int, TPixel> func) {
var result = new TPixel[width,height];
From(0, width).ToList().ForEach(y =>
From(0, height).ToList().ForEach(x => result[x, y] = func(x, y)));
return result; }
// convolution with wrapping
static double[,] Convolve(this double[,] kernel, double[,] pixels) {
var kcx = kernel.Width() / 2;
var kcy = kernel.Height() / 2;
return FromFunc(pixels.Width(), pixels.Height(),
(x, y) => kernel.Select((kx, ky) => pixels.Pixel(x + kx - kcx, y + ky - kcy) * kernel[kx, ky])
.Aggregate((sum, px) => sum + px)); }
// gabor stimulus generators
static double[,] Gabor(int width, int height, double r0) =>
FromFunc<double>(width, height, (x, y) => x * y);
// non-cartesian stimulus generator </summary>
static double[,] Pinwheel(int width, int height, double r0) =>
FromFunc<double>(width, height, (x, y) => x * y);
// load an image from a file</summary>
static TPixel[,] Load<TPixel>(string filename) => null;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment