/// <summary> /// Loads a texture from a file /// </summary> /// <param name="filename">The file from which to get the texture</param> /// <returns>If it loaded the texture correctly</returns> public bool Load(string filename) { FileStream fs = new FileStream(filename, FileMode.Open); BinaryReader br = new BinaryReader(fs); //Read the size int sizex = br.ReadInt32(); int sizey = br.ReadInt32(); this.Scale(sizex, sizey); //Scale to new size ComponentEditor.ModifyAll(this,null); //And clear //Read textures int totalPixels = br.ReadInt32(); for (int i = 0; i < totalPixels; i++ ) { int x = br.ReadInt32(); int y = br.ReadInt32(); char c = (char)br.ReadInt32(); ConsoleColor f = (ConsoleColor)br.ReadInt32(); ConsoleColor b = (ConsoleColor)br.ReadInt32(); Contents[x, y] = new Pixel(c, f, b); } return true; }
//=========================================================================================== public static void AreNotEqual(Pixel expected, Pixel actual) { Assert.IsNotNull(expected); Assert.IsNotNull(actual); AreNotEqual(expected.ToColor(), actual.ToColor()); }
public override void FrameSet(Pixel pixel, int position) { if (position < 0) { return; } int currentRow = position / (int)(NumberOfPanels * ColumnsPerPanel); int currentColumn = position % (int)(NumberOfPanels * ColumnsPerPanel); Frame[PointPostion(currentRow, currentColumn)] = pixel; }
private static Pixel MergeRgb(Pixel p0, Pixel p1, Pixel p2) { var from = (p0 + p1 + p2) / 3; var to = new Pixel(p0.C0, p1.C1, p2.C2, from.C3); var p = 1.0; return from + (to - from) * p; }
private static int ColorHash(Pixel colour) { int num = 0; if (colour.A > 0) { num = (((((0xff - colour.R) * 0x100) * 0x100) + ((0xff - colour.G) * 0x100)) + (0xff - colour.B)) + 1; } return num; }
public void SetPixel( int x, int y, Pixel colour ) { if ( Image.TiledView ) { x = Wrap( x, Image.Width ); y = Wrap( y, Image.Height ); } Pixels[ x, y ] = colour; DrawPixel( x, y ); }
Tuple<int, int> GetLowerUpper(Pixel trimColor, IEnumerable<Pixel[]> array, string lower, string upper) { Predicate<bool> notTrue = (b) => {return !b;}; var rows = array.Select(x => AllEqual(x, trimColor)).ToList(); return Tuple.Create((GetValue<bool>(lower)) ? rows.FindIndex(notTrue) : 0, (GetValue<bool>(upper)) ? rows.FindLastIndex(notTrue) + 1 : rows.Count()); }
//эта штука нужна, если мы попали на границу нашей картинки. Мы не можем взять 4 точки для интерполяции, поэтому берём только две private double LinearInterpolate(Pixel first, Pixel second, double x, double y) { if (first == null || second == null)//если вдруг мы попали в угол картинки. У нас не будет даже двух точек - будет всего одна return (first ?? second).Intensity; if (first.Y == second.Y) return Math.Abs((second.X - x) * first.Intensity + (x - first.X) * second.Intensity); if (first.X == second.X) return Math.Abs((second.Y - y) * first.Intensity + (y - first.Y) * second.Intensity); throw new Exception("Somthing wrong :)"); }
double[,] Normalize(ref Pixel x) { //Gaussian distribution double[,] Px_i = new double[NumofClasses, NumofFeatures]; for (int i = 0; i < NumofClasses; ++i) { Px_i[i, 0] = ((double)1 / Math.Sqrt(2 * Math.PI) * Sigma[i,0]) * Math.Exp(-Math.Pow((x.R - Mu[i,0]), 2) / (2 * Math.Pow(Sigma[i,0], 2))); Px_i[i, 1] = ((double)1 / Math.Sqrt(2 * Math.PI) * Sigma[i,1]) * Math.Exp(-Math.Pow((x.G - Mu[i,1]), 2) / (2 * Math.Pow(Sigma[i,1], 2))); Px_i[i, 2] = ((double)1 / Math.Sqrt(2 * Math.PI) * Sigma[i,2]) * Math.Exp(-Math.Pow((x.B - Mu[i,2]), 2) / (2 * Math.Pow(Sigma[i,2], 2))); } return Px_i; }
public void ContainsCornerPixelsTest() { var _Rectangle = new Rectangle<Double>(10, 20, 30, 40); var _Pixel1 = new Pixel<Double>(10, 20); var _Pixel2 = new Pixel<Double>(30, 20); var _Pixel3 = new Pixel<Double>(10, 40); var _Pixel4 = new Pixel<Double>(30, 40); Assert.IsTrue(_Rectangle.Contains(_Pixel1)); Assert.IsTrue(_Rectangle.Contains(_Pixel2)); Assert.IsTrue(_Rectangle.Contains(_Pixel3)); Assert.IsTrue(_Rectangle.Contains(_Pixel4)); }
public void Filter(IImage image, double[,] filter) { if (filter.GetLength(0) != filter.GetLength(1)) { throw new ArgumentException("invalid filter", nameof(filter)); } var result = new Pixel[image.Width, image.Height]; double blue = 0.0; double green = 0.0; double red = 0.0; int filterOffset = (filter.GetLength(0) - 1) / 2; for (int offsetY = filterOffset; offsetY < image.Height - filterOffset; offsetY++) { for (int offsetX = filterOffset; offsetX < image.Width - filterOffset; offsetX++) { blue = 0; green = 0; red = 0; for (int filterY = -filterOffset; filterY <= filterOffset; filterY++) { for (int filterX = -filterOffset; filterX <= filterOffset; filterX++) { var imagePixel = image.GetPixel(offsetX + filterX, offsetY + filterY); blue += (double)(imagePixel.B) * filter[filterY + filterOffset, filterX + filterOffset]; green += (double)(imagePixel.G) * filter[filterY + filterOffset, filterX + filterOffset]; red += (double)(imagePixel.R) * filter[filterY + filterOffset, filterX + filterOffset]; } } blue = Factor * blue + Bias; green = Factor * green + Bias; red = Factor * red + Bias; result[offsetX, offsetY] = new Pixel { R = this.ToByte(red), G = this.ToByte(green), B = this.ToByte(blue) }; } } for (int x = 0; x < result.GetLength(0); x++) { for (int y = 0; y < result.GetLength(1); y++) { image.SetPixel(x, y, result[x, y]); } } }
public void ProcessImage(IImage inputImage) { var segments = _segmentationAlgoritm.ProcessImage(inputImage); var image = segments.SegmentationMatrix; for (int j = 0; j < inputImage.Height; j++) { for (int i = 0; i < inputImage.Width; i++) { var random = new Random(image[i, j]); var pixel = new Pixel { R = (byte)random.Next(255), G = (byte)random.Next(255), B = (byte)random.Next(255) }; inputImage.SetPixel(i, j, pixel); } } }
private byte GetForColorizer(Pixel p) { byte b = unchecked((byte)(Math.Floor((double)(getForPallet(p.R) / (byte)42)) * Math.Floor((double)(getForPallet(p.G) / (byte)42)) * Math.Floor((double)(getForPallet(p.B) / (byte)42)))); if (b == 0) { return 1; } else if (b == 1) { return 0; } else { return unchecked((byte)(b + (byte)2)); } }
public void ReadCurrentRow__moves_through_complete_row() { var p = new Pixel(50, 25); var called = 0; var reader = new Mock<IImageReader>(); reader.Setup(i => i.CurrentPixelType()).Returns(PixelType.Water); reader.Setup(i => i.NextRow()).Returns(() => { called++; return called < 50; }); reader.Setup(i => i.CurrentPixel).Returns(p); reader.Setup(i => i.FrameHeight).Returns(50); var imageParser = new ImageParser(reader.Object); var res = imageParser.ReadCurrentRow(); res.Should().Be(p); called.Should().BeGreaterOrEqualTo(49); }
public Renderer(VariableSet variables, Drawable drawable) : base(variables) { _drawable = drawable; int bpp = drawable.Bpp; _pixel = drawable.CreatePixel(); _color = GetValue<bool>("color"); if (drawable.HasAlpha) { bpp--; _pixel.Alpha = 255; } _calculator = new Calculator(GetValue<int>("points"), GetValue<int>("closest"), bpp, drawable.MaskBounds, (int) GetValue<UInt32>("seed")); }
public void ConstructorTests() { var m = new Matrix<Pixel>( new Pixel(1, 1, 1, 1), new Pixel(1, 1, 2, 2), new Pixel(2, 2, 1, 1), new Pixel(2, 2, 2, 2)); for(var i = 0; i < m.Width; i++) { var x = (byte)(i + 1); for (var j = 0; j < m.Height; j++) { var y = (byte)(j + 1); var p = new Pixel(y, y, x, x); Trace.WriteLine($"[{x}, {y}]: {p} == {m[i,j]}"); Assert.AreEqual(m[i, j], p, $"{m[i, j]} <> {p}\n{m}"); } } }
public int Classify(ref Pixel features, ref double[,] loss) { double[,] pxjwi = Normalize(ref features); double[] pxwi = new double[NumofClasses]; for (int i = 0; i < NumofClasses; ++i) { pxwi[i] = 1; for (int j = 0; j < NumofFeatures; ++j) pxwi[i] *= pxjwi[i, j]; } double sum = 0; for (int i = 0; i < NumofClasses; ++i) { pxwi[i] *= PClasses; sum += pxwi[i]; } for (int i = 0; i < NumofClasses; ++i) { pxwi[i] /= sum; } double[] r = new double[NumofActions]; for (int i = 0; i < NumofActions; ++i) { sum = 0; for (int j = 0; j < NumofClasses; ++j) sum += loss[i,j] * pxwi[j]; r[i] = sum; } // Return the index of the lowest risk of the N Actions double x = int.MaxValue; int ind = 0; for (int i = 0; i < NumofActions; ++i) if (x > r[i]) { x = r[i]; ind = i; } return ind; }
public Layer( ImageInfo image, String label = null ) { Image = image; if ( label == null ) { int i = 1; while ( image.Layers.Exists( x => x.Label.ToLower().Equals( "layer " + i ) ) ) ++i; label = "layer " + i; } Label = label; Pixels = new Pixel[ Width, Height ]; Bitmap = new Bitmap( Width, Height ); for ( int x = 0; x < Width; ++x ) for ( int y = 0; y < Height; ++y ) SetPixel( x, y, Pixel.Empty ); }
public override void Write(Pixel[] frame) { ulong[] outputGreen = new ulong[PanelsPerFrame]; ulong[] outputRed = new ulong[PanelsPerFrame]; ulong pixelStateGreen = 0; ulong pixelStateRed = 0; for (int panels = 0; panels < PanelsPerFrame; panels++) { for (int i = panels * 64; i < 64 + (panels * 64); i++) { switch (frame[i].ColourValue) { case 65280: // green pixelStateGreen = 1UL; pixelStateGreen = pixelStateGreen << i; outputGreen[panels] = outputGreen[panels] | pixelStateGreen; break; case 16711680: // red pixelStateRed = 1UL; pixelStateRed = pixelStateRed << i; outputRed[panels] = outputRed[panels] | pixelStateRed; break; case 16776960: //yellow pixelStateGreen = 1UL; pixelStateGreen = pixelStateGreen << i; outputGreen[panels] = outputGreen[panels] | pixelStateGreen; pixelStateRed = 1UL; pixelStateRed = pixelStateRed << i; outputRed[panels] = outputRed[panels] | pixelStateRed; break; } } } Write(outputGreen, outputRed); }
static void Main(string[] args) { while (true) { Console.WriteLine("Username:"******" "); if ((i + 1) % 4 == 0) { Console.WriteLine(); Console.BackgroundColor = ConsoleColor.Black; } } } }
private void ConvertToPixels() { int w = Bitmap.PixelWidth; int h = Bitmap.PixelHeight; int stride = Bitmap.BackBufferStride; int size = stride * h; Pixels = new Pixel[h,w]; Bitmap.Lock(); unsafe { var pixels = (byte*)Bitmap.BackBuffer; int i=0; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++, i += 4) { Pixels[y, x] = new Pixel(pixels[i+2],pixels[i+1],pixels[i]); } } } // Bitmap.AddDirtyRect(new Int32Rect(0, 0, w, h)); Bitmap.Unlock(); }
private void Fill(Point position, Pixel oldColor) { var front = new Queue<Point>(); front.Enqueue(position); while (front.Count > 0) { Point point = front.Dequeue(); if (GetPixel(point) == oldColor) { SetPixel(point.X, point.Y); if (point.X > 0) front.Enqueue(new Point(point.X - 1, point.Y)); if (point.X < 599) front.Enqueue(new Point(point.X + 1, point.Y)); if (point.Y > 0) front.Enqueue(new Point(point.X, point.Y - 1)); if (point.Y < 599) front.Enqueue(new Point(point.X, point.Y + 1)); } } }
private void EvaluateCurrentColor() { double rC = Math.Floor(_bucketColor.Sum(color => color.R)/(double) _bucketColor.Count); double gC = Math.Floor(_bucketColor.Sum(color => color.G)/(double) _bucketColor.Count); double bC = Math.Floor(_bucketColor.Sum(color => color.B)/(double) _bucketColor.Count); double aC = Math.Floor(_bucketAlpha.Sum(color => color)/(double) _bucketAlpha.Count); if (_bucketAlpha.Count == 0) aC = 255; if (_bucketColor.Count == 0) { rC = gC = bC = 0; } _currentColor = new Pixel(Color.FromArgb((int) Math.Floor(rC*aC/255.0), (int) Math.Floor(gC*aC/255.0), (int) Math.Floor(bC*aC/255.0)), (byte) Math.Floor(aC)); }
private static PixelMap CreateTransperentBitmap() { var result = new PixelMap(); for (int x = 0; x < 600; ++x) for (int y = 0; y < 600; ++y) { result[x,y] = new Pixel(_black, _transparent); } return result; }
/// <summary> /// Return the child index for a given color. /// Depends on which level this node is in. /// </summary> /// <param name="pixel">color pixel to compute</param> /// <returns>child index (0-7)</returns> private int GetChildIndex(Pixel pixel) { // lvl: 0 1 2 3 4 5 6 7 // bit: 7 6 5 4 3 2 1 0 var shift = 7 - this.nodeLevel; int mask = NodeLevelMasks[this.nodeLevel]; return ((pixel.Red & mask) >> (shift - 2)) | ((pixel.Green & mask) >> (shift - 1)) | ((pixel.Blue & mask) >> shift); }
/// <summary> /// Given a source color, return the palette index to use for the reduced image. /// Returns -1 if the color is not represented in the octree (this happens if /// the color has been dithered into a new color that did not appear in the /// original image when the octree was formed in pass 1. /// </summary> /// <param name="pixel">source color to look up</param> /// <returns>palette index to use</returns> internal int GetPaletteIndex(Pixel pixel) { int paletteIndex = -1; if (this.nodeIsLeaf) { // Use this leaf node's palette index paletteIndex = this.nodePaletteIndex; } else { // Get the index at this level for the rgb values var childIndex = this.GetChildIndex(pixel); if (this.nodeChildNodes[childIndex] != null) { // Recurse... paletteIndex = this.nodeChildNodes[childIndex].GetPaletteIndex(pixel); } } return paletteIndex; }
/// <summary> /// Add the given color to this node if it is a leaf, otherwise recurse /// down the appropriate child /// </summary> /// <param name="pixel">color to add</param> /// <returns>true if a new color was added to the octree</returns> internal bool AddColor(Pixel pixel) { bool colorAdded; if (this.nodeIsLeaf) { // Increase the pixel count for this node, and if // the result is 1, then this is a new color colorAdded = ++this.nodePixelCount == 1; // Add the color to the running sum for this node this.nodeRedSum += pixel.Red; this.nodeGreenSum += pixel.Green; this.nodeBlueSum += pixel.Blue; // Set the last node so we can quickly process adjacent pixels // with the same color this.nodeOctree.SetLastNode(this, pixel.Argb); } else { // Get the index at this level for the rgb values int childIndex = this.GetChildIndex(pixel); // If there is no child, add one now to the next level if (this.nodeChildNodes[childIndex] == null) { this.nodeChildNodes[childIndex] = new OctreeNode(this.nodeLevel + 1, this.nodeOctree); } // Recurse... colorAdded = this.nodeChildNodes[childIndex].AddColor(pixel); } return colorAdded; }
/// <summary> /// Given a pixel color, return the index of the palette entry /// we want to use in the reduced image. If the color is not in the /// octree, OctreeNode.GetPaletteIndex will return a negative number. /// In that case, we will have to calculate the palette index the brute-force /// method by computing the least distance to each color in the palette array. /// </summary> /// <param name="pixel">pointer to the pixel color we want to look up</param> /// <returns>index of the palette entry we want to use for this color</returns> internal int GetPaletteIndex(Pixel pixel) { int paletteIndex = 0; // transparent is always the first entry, so if this is transparent, // don't do anything. if (pixel.Alpha > 0) { paletteIndex = this.octreeRoot.GetPaletteIndex(pixel); // returns -1 if this value isn't in the octree. if (paletteIndex < 0) { // Use the brute-force method of calculating the closest color // in the palette to the one we want int minDistance = int.MaxValue; for (int ndx = 0; ndx < this.octreePalette.Length; ++ndx) { Color paletteColor = this.octreePalette[ndx]; // Calculate the delta for each channel int deltaRed = pixel.Red - paletteColor.R; int deltaGreen = pixel.Green - paletteColor.G; int deltaBlue = pixel.Blue - paletteColor.B; // Calculate the distance-squared by summing each channel's square int distance = (deltaRed * deltaRed) + (deltaGreen * deltaGreen) + (deltaBlue * deltaBlue); if (distance < minDistance) { minDistance = distance; paletteIndex = ndx; } } } } return paletteIndex; }
/// <summary>Add the given pixel color to the octree</summary> /// <param name="pixel">points to the pixel color we want to add</param> internal void AddColor(Pixel pixel) { // If the A value is non-zero (ignore the transparent color) if (pixel.Alpha > 0) { // If we have a previous node and this color is the same as the last... if (this.octreeLastNode != null && pixel.Argb == this.octreeLastArgb) { // Just add this color to the same last node this.octreeLastNode.AddColor(pixel); } else { // Just start at the root. If a new color is added, // add one to the count (otherwise 0). this.octreeColorCount += this.octreeRoot.AddColor(pixel) ? 1 : 0; } } else { // Flag that we have a transparent color. this.octreeHasTransparent = true; } }
public void Render(Image image, Drawable drawable) { var parser = new MathExpressionParser(); parser.Init(GetValue<string>("formula"), image.Dimensions); var newImage = new Image(image.Dimensions, image.BaseType); var srcPR = new PixelRgn(drawable, image.Bounds, false, false); PixelRgn destPR1 = null; var layer1 = AddLayer(newImage, 1, _("layer_one"), "translate_1_x", "translate_1_y", out destPR1); PixelRgn destPR2 = null; var layer2 = AddLayer(newImage, 2, _("layer_two"), "translate_2_x", "translate_2_y", out destPR2); var transparent = new Pixel(4); if (destPR1 != null && destPR2 != null) { var iterator = new RegionIterator(srcPR, destPR1, destPR2); iterator.ForEach((src, dest1, dest2) => { var tmp = Copy(src); if (parser.Eval(src) < 0) { dest1.Set(tmp); dest2.Set(transparent); } else { dest2.Set(tmp); dest1.Set(transparent); } }); } else if (destPR1 != null) { var iterator = new RegionIterator(srcPR, destPR1); iterator.ForEach((src, dest) => dest.Set((parser.Eval(src) < 0) ? Copy(src) : transparent)); } else // destPR2 != null { var iterator = new RegionIterator(srcPR, destPR2); iterator.ForEach((src, dest) => dest.Set((parser.Eval(src) >= 0) ? Copy(src) : transparent)); } Rotate(layer1, GetValue<int>("rotate_1")); Rotate(layer2, GetValue<int>("rotate_2")); if (GetValue<bool>("merge")) { var merged = newImage.MergeVisibleLayers(MergeType.ExpandAsNecessary); merged.Offsets = new Offset(0, 0); newImage.Resize(merged.Dimensions, merged.Offsets); } new Display(newImage); Display.DisplaysFlush(); }