예제 #1
0
 public static void SetPixel(this EmguImage img, int x, int y, Color color)
 {
     img.Data[y, x, 0] = (byte)color.Red;
     img.Data[y, x, 1] = (byte)color.Green;
     img.Data[y, x, 2] = (byte)color.Blue;
     img.Data[y, x, 3] = (byte)color.Alpha;
 }
예제 #2
0
        public static void SetPixels(this EmguImage img, Rectangle area, Color[] pixels)
        {
            // Area dimensions
            int xStart = area.X;
            int xEnd   = xStart + area.Width;
            int yStart = area.Y;
            int yEnd   = yStart + area.Height;

            // Area checks
            if (xStart < 0 || xEnd > img.Width || yStart < 0 || yEnd > img.Height)
                throw new ArgumentOutOfRangeException("area", area, "The are does not fill in the image");

            if (area.Width * area.Height != pixels.Length)
                throw new ArgumentOutOfRangeException("pixels", pixels, "Invalid number of pixels");

            // Data, it's faster not to iterate over a property
            byte[,,] data = img.Data;

            // Assign color to each pixel
            for (int y = yStart; y < yEnd; y++) {
                for (int x = xStart; x < xEnd; x++) {
                    // TEMP: Swap blue and red due to odd bug of Emug.CV
                    int cIdx = (y - yStart) * area.Width + (x - xStart);
                    data[y, x, 0] = (byte)pixels[cIdx].Blue;
                    data[y, x, 1] = (byte)pixels[cIdx].Green;
                    data[y, x, 2] = (byte)pixels[cIdx].Red;
                    data[y, x, 3] = (byte)pixels[cIdx].Alpha;
                }
            }
        }
예제 #3
0
        public EmguImage CreateBitmap(Image image, Palette palette)
        {
            EmguImage  bitmap     = new EmguImage(512, 256);
            List <Obj> sortedObjs = new List <Obj>(this.objects);

            sortedObjs.Sort((a, b) => b.GetPriority().CompareTo(a.GetPriority()));

            foreach (Obj obj in sortedObjs)
            {
                EmguImage objBitmap = obj.CreateBitmap(image, palette, this.tileSize);

                // Get first palette color
                Color transparent = palette.GetColor(obj.PaletteIndex, 0);

                // Set first palette color as transparent
                var mask = objBitmap.InRange(transparent, transparent);
                objBitmap.SetValue(0, mask);

                // Copy the object image to the frame
                Point position = obj.GetReferencePoint();
                position.Offset(256, 128);                      // Only positive coordinate values
                bitmap.Overlay(position.X, position.Y, objBitmap);

                objBitmap.Dispose();
            }

            //Rectangle absArea = this.VisibleArea;
            //absArea.Offset(512, 128); // Only positive coordinate values
            //EmguImage roiBitmap = bitmap.Copy(absArea);
            //bitmap.Dispose();
            return(bitmap);
        }
예제 #4
0
 public static void SetPixel(this EmguImage img, int x, int y, Color color)
 {
     img.Data[y, x, 0] = (byte)color.Red;
     img.Data[y, x, 1] = (byte)color.Green;
     img.Data[y, x, 2] = (byte)color.Blue;
     img.Data[y, x, 3] = (byte)color.Alpha;
 }
예제 #5
0
        private void MoveBackdropColor()
        {
            // Move the backdrop color to the first position
            int idx = Array.FindIndex <Color>(this.Palette, c => c.Equals(this.BackdropColor));

            if (idx == -1)
            {
                return;
            }

            // Swap color
            Color swap = this.Palette[0];

            this.Palette[0]   = this.Palette[idx];
            this.Palette[idx] = swap;

            // Change pixel info
            Pixel[] pixels = this.Pixels;
            for (int i = 0; i < pixels.Length; i++)
            {
                if (pixels[i].Info == idx)
                {
                    pixels[i] = pixels[i].ChangeInfo(0);
                }
                else if (pixels[i].Info == 0)
                {
                    pixels[i] = pixels[i].ChangeInfo((uint)idx);
                }
            }
        }
예제 #6
0
        private static void ExportTextureWithColors(string n3dPath, string outPath, string colors)
        {
            string name = Path.GetFileNameWithoutExtension(n3dPath);
            string path = Path.Combine(outPath, name);

            // Get texture file
            Npck pack    = new Npck(n3dPath);
            Btx0 texture = new Btx0(pack[0]);

            // Parse colors
            string[] strColors = colors.Split(' ');
            Color[]  newColors = new Color[strColors.Length];
            for (int i = 0; i < strColors.Length; i++)
            {
                int hexColor = Convert.ToInt32(strColors[i], 16);
                newColors[i]       = new Color();
                newColors[i].Alpha = 255;
                newColors[i].Red   = (hexColor >> 00) & 0xFF;
                newColors[i].Green = (hexColor >> 08) & 0xFF;
                newColors[i].Blue  = (hexColor >> 16) & 0xFF;
            }

            // Create and export palette
            Palette palette = new Palette(newColors);

            palette.ToWinPaletteFormat(path + "_palGimp.pal", 0, true);
            palette.ToWinPaletteFormat(path + "_pal.pal", 0, false);
            palette.CreateBitmap(0).Save(path + "_pal.png");

            // For each image, set new palette and export it
            for (int i = 0; i < texture.NumTextures; i++)
            {
                texture.CreateBitmap(i, palette).Save(path + "_" + i.ToString() + ".png");
            }
        }
예제 #7
0
        public static EmguImage CreateBitmap(Color[] colors)
        {
            int height = (colors.Length / 0x10);
            if (colors.Length % 0x10 != 0)
                height++;

            EmguImage palette = new EmguImage(160, height * 10);

            bool end = false;
            for (int i = 0; i < 16 & !end; i++) {
                for (int j = 0; j < 16; j++) {
                    // Check if we have reached the end.
                    // A palette image can be incompleted (number of colors not padded to 16)
                    if (colors.Length <= j + 16 * i) {
                        end = true;
                        break;
                    }

                    for (int k = 0; k < 10; k++)
                        for (int q = 0; q < 10; q++)
                            palette.SetPixel(j * 10 + q, i * 10 + k, colors[j + 16 * i]);
                }
            }

            return palette;
        }
예제 #8
0
        protected override Pixel QuantizatePixel(int x, int y)
        {
            // Get the color and add to the list
            Color color = image[y, x];

            int colorIndex;

            if (listColor.Count < this.MaxColors)
            {
                if (!listColor.Contains(color))
                {
                    listColor.Add(color);
                }
                colorIndex = listColor.IndexOf(color);
            }
            else
            {
                // Create the labpalette if so
                if (nearestNeighbour == null)
                {
                    LabColor[] labPalette = ColorConversion.ToLabPalette <Color>(listColor.ToArray());
                    nearestNeighbour = new ExhaustivePaletteSearch();
                    nearestNeighbour.Initialize(labPalette);
                }

                LabColor labNoTrans = ColorConversion.ToLabPalette <Color>(new Color[] { color })[0];
                colorIndex = nearestNeighbour.Search(labNoTrans);
            }

            return(new Pixel((uint)colorIndex, (uint)color.Alpha, true));
        }
예제 #9
0
        private static Color[][] DividePalette(int numColors, int numPalettes, Color[] palette, ushort[] index = null)
        {
            if (index != null && index.Length != numPalettes)
            {
                throw new ArgumentOutOfRangeException();
            }

            Color[][] newPalettes;
            if (index != null && index.Length > 0)
            {
                newPalettes = new Color[index.Max() + 1][];
            }
            else
            {
                newPalettes = new Color[numPalettes][];
            }
            for (int i = 0; i < newPalettes.Length; i++)
            {
                newPalettes[i] = new Color[0];
            }

            // Set the right palette
            int totalColors = palette.Length;

            for (int i = 0; i < numPalettes; i++)
            {
                int idx        = (index != null) ? index[i] : i;
                int copyColors = ((i + 1) * numColors < totalColors) ? numColors : totalColors - i * numColors;
                newPalettes[idx] = new Color[copyColors];
                Array.Copy(palette, i * numColors, newPalettes[idx], 0, copyColors);
            }

            return(newPalettes);
        }
        protected override Pixel QuantizatePixel(int x, int y)
        {
            // Get nearest color from palette
            int colorIndex = nearestNeighbour.Search(labImg[y, x]);

            // Apply dithering algorithm for each channel
            LabColor oldPixel = labImg[y, x];
            LabColor newPixel = labPalette[colorIndex];

            this.Dithering.ApplyDithering(labImg.Data, x, y, 0, oldPixel.X - newPixel.X);
            this.Dithering.ApplyDithering(labImg.Data, x, y, 1, oldPixel.Y - newPixel.Y);
            this.Dithering.ApplyDithering(labImg.Data, x, y, 2, oldPixel.Z - newPixel.Z);

            // If it's a transparent color, set the first palette color
            Color rgbColor = this.rgbImg[y, x];

            if (rgbColor.Alpha == 0)
            {
                return(new Pixel(0, 0, true));
            }
            else
            {
                return(new Pixel((uint)colorIndex, (uint)rgbColor.Alpha, true));
            }
        }
예제 #11
0
        public static ushort ToBgr555(this Color color)
        {
            int red   = (int)(color.Red / 8);
            int green = (int)(color.Green / 8);
            int blue  = (int)(color.Blue / 8);

            return((ushort)((red << 0) | (green << 5) | (blue << 10)));
        }
예제 #12
0
 public override double distance(Emgu.CV.Structure.Bgra color, IColorComparison comp, byte transparencyThreshold)
 {
     if (count == 0)
     {
         return(Int32.MaxValue);
     }
     return(comp.Distance(color.ToLab(), labColor));
 }
예제 #13
0
 public static Color[] ToArgbColors(this uint[] argb)
 {
     Color[] colors = new Color[argb.Length];
     for (int i = 0; i < argb.Length; i++)
     {
         colors[i] = argb[i].ToArgbColor();
     }
     return(colors);
 }
예제 #14
0
 private static Color[] InfoToIndexedColors(uint[] colorInfo, Color[][] palettes, uint[] palIdx)
 {
     Color[] colors = new Color[colorInfo.Length];
     for (int i = 0; i < colorInfo.Length; i++)
     {
         colors[i] = InfoToIndexedColor(colorInfo[i], palettes[palIdx[i]]);
     }
     return(colors);
 }
예제 #15
0
        public static int CalculateDifferentsColors(Color[] palette1, Color[] palette2)
        {
            int count = 0;
            foreach (Color c in palette1)
                if (!palette2.Contains(c))
                    count++;

            return count;
        }
예제 #16
0
 public static uint ToArgb(this Color color)
 {
     return((uint)(
                ((byte)color.Red << 16) |
                ((byte)color.Green << 08) |
                ((byte)color.Blue << 00) |
                ((byte)color.Alpha << 24)
                ));
 }
예제 #17
0
 public override double distance(Emgu.CV.Structure.Bgra color, IColorComparison comp, byte transparencyThreshold)
 {
     if (color.Alpha < transparencyThreshold)
     {
         return(0);
     }
     else
     {
         return(Int32.MaxValue);
     }
 }
        public ManyFixedPaletteQuantization(Color[][] palettes)
            : base(palettes[0])
        {
            this.compareQuantization = new BasicQuantization();
            this.palettes = palettes;

            if (palettes.Length > 1) {
                this.labPalettes = new LabColor[palettes.Length][];
                for (int i = 0; i < palettes.Length; i++)
                    labPalettes[i] = ColorConversion.ToLabPalette<Color>(palettes[i]);
            }
        }
예제 #19
0
 public static int CompareTo(this Color c1, Color c2)
 {
     if (c1.Red == c2.Red) {
         if (c1.Green == c2.Green) {
             return c1.Blue.CompareTo(c2.Blue);
         } else {
             return c1.Green.CompareTo(c2.Green);
         }
     } else {
         return c1.Red.CompareTo(c2.Red);
     }
 }
예제 #20
0
        private static void SearchPalette(string packPath, string imgPath, int idx)
        {
            // Get new image
            EmguImage newImg = new EmguImage(imgPath);

            // Get original image
            Npck  pack        = new Npck(packPath);
            Btx0  texture     = new Btx0(pack[0]);
            Image originalImg = texture.GetImage(idx);

            Pixel[] pixels = originalImg.GetPixels();

            // For each pixel, set palette color in the position given by original image
            Color[] palette = new Color[originalImg.Format.MaxColors()];
            for (int y = 0; y < newImg.Height; y++)
            {
                for (int x = 0; x < newImg.Width; x++)
                {
                    // Get target color
                    Color px = newImg[y, x];

                    // Get palette color index
                    uint index = pixels[y * newImg.Width + x].Info;

                    // If we have already set this color, and it does not match with
                    // this pixel... Error!
                    if (palette[index].Alpha != 0 && !palette[index].Equals(px))
                    {
                        Console.WriteLine("Can not find a valid color combination");
                        return;
                    }

                    // If the color has not been set, set it!
                    if (palette[index].Alpha == 0)
                    {
                        palette[index] = px;
                    }
                }
            }

            // Print palette
            Console.WriteLine("Palette found");
            string xmlColor = "          <Color red=\"{0}\" green=\"{1}\" blue=\"{2}\" />";

            foreach (Color c in palette)
            {
                Console.WriteLine(xmlColor, c.Red, c.Green, c.Blue);
            }
        }
예제 #21
0
        public static Color[] ToBgr555Colors(this byte[] values)
        {
            if (values.Length % 2 != 0)
            {
                throw new ArgumentException("Length must be even.");
            }

            Color[] colors = new Color[values.Length / 2];
            for (int i = 0; i < colors.Length; i++)
            {
                colors[i] = BitConverter.ToUInt16(values, i * 2).ToBgr555Color();
            }

            return(colors);
        }
예제 #22
0
        public EmguImage CreateBitmap(int texIdx, Palette palette)
        {
            // Get image
            EmguImage img = this.images[texIdx].CreateBitmap(palette, 0);

            // Set transparent color
            if (this.tex0.TextureInfo.Data[texIdx].Color0)
            {
                Color transparent = palette.GetPalette(0)[0];
                var   mask        = img.InRange(transparent, transparent);
                img.SetValue(0, mask);
            }

            return(img);
        }
예제 #23
0
        private static Color InfoToIndexedColor(uint colorInfo, Color[] palette)
        {
            uint alpha      = colorInfo >> 24;
            uint colorIndex = colorInfo & 0x00FFFFFF;

            if (colorIndex >= palette.Length)
            {
                throw new IndexOutOfRangeException("Color index out of palette");
            }

            Color color = palette[colorIndex];

            color.Alpha = (double)alpha;

            return(color);
        }
예제 #24
0
        public static double CalculateDistance(Color[] palette1, Color[] palette2)
        {
            double totalDistance = 0;

            for (int i = 0; i < palette1.Length; i++) {
                double minColorDistance = -1;
                for (int j = 0; j < palette2.Length; j++) {
                    double distance = palette1[i].GetDistanceSquared(palette2[j]);
                    if (minColorDistance == -1 || distance < minColorDistance)
                        minColorDistance = distance;
                }

                totalDistance += minColorDistance;
            }

            return totalDistance;
        }
예제 #25
0
 public static int CompareTo(this Color c1, Color c2)
 {
     if (c1.Red == c2.Red)
     {
         if (c1.Green == c2.Green)
         {
             return(c1.Blue.CompareTo(c2.Blue));
         }
         else
         {
             return(c1.Green.CompareTo(c2.Green));
         }
     }
     else
     {
         return(c1.Red.CompareTo(c2.Red));
     }
 }
예제 #26
0
        private void SortPalette()
        {
            // Sort palette
            Color[] palette      = this.Palette;
            Color[] messyPalette = (Color[])palette.Clone();
            Array.Sort <Color>(palette, (c1, c2) => c1.CompareTo(c2));
            this.Palette = palette;

            // Update pixel index
            Pixel[] pixels = this.Pixels;
            for (int i = 0; i < pixels.Length; i++)
            {
                Color oldColor = messyPalette[pixels[i].Info];
                int   newIndex = Array.FindIndex <Color>(palette, c => c.Equals(oldColor));

                pixels[i] = pixels[i].ChangeInfo((uint)newIndex);
            }
        }
예제 #27
0
        public void AddImage(EmguImage newImg, string name, Color[] palOut = null)
        {
            if (newImg == null)
                throw new ArgumentNullException();

            // First, let's be sure the dimension are power of 2.
            if (!IsPowerOfTwo((uint)newImg.Width)) {
                int width = 1 << (int)(Math.Log(newImg.Width, 2) + 1);
                EmguImage blankVertical = new EmguImage(width - newImg.Width, newImg.Height);
                newImg = newImg.ConcateHorizontal(blankVertical);
                Console.Write("(Warning: Width not power of 2) ");
            }

            if (!IsPowerOfTwo((uint)newImg.Height)) {
                int height = 1 << (int)(Math.Log(newImg.Height, 2) + 1);
                EmguImage blankHorizontal = new EmguImage(newImg.Width, height - newImg.Height);
                newImg = newImg.ConcateVertical(blankHorizontal);
                Console.Write("(Warning: Height not power of 2) ");
            }

            // Quantizate image -> get pixels and palette
            this.Quantization.Quantizate(newImg);
            Pixel[] pixels = this.Quantization.GetPixels(PixelEncoding.Lineal);
            Color[] colors = (palOut == null) ? this.Quantization.Palette : palOut;

            int maxColors = this.Format.MaxColors();
            if (colors.Length > maxColors)
                throw new FormatException(string.Format("The image has more than {0} colors", maxColors));

            // Create image format
            Image image = new Image();
            image.Width = newImg.Width;
            image.Height = newImg.Height;
            image.SetData(pixels, PixelEncoding.Lineal, this.Format, new Size(1, 1));

            // Create the palette
            Palette palette = new Palette(colors);

            // Add the image
            this.Texture.AddImage(image, palette, name);
        }
예제 #28
0
        private static Difference[] CalculateDifferentsColors(Color[][] palettes, int idx)
        {
            // Combination of the palette with other palette except with itself
            Difference[] distances = new Difference[palettes.Length - 1];

            // Compute every possible difference
            int j = 0;
            for (int i = 0; i < palettes.Length; i++) {
                if (idx == i)
                    continue;

                distances[j] = new Difference();
                distances[j].SrcPalette = idx;
                distances[j].DstPalette = i;
                distances[j].Distance = PaletteDistance.CalculateDifferentsColors(
                    palettes[idx], palettes[i]);
                j++;
            }

            return distances;
        }
예제 #29
0
파일: Nclr.cs 프로젝트: pleonex/ninoimager
 public void SetData(Color[] palette, ColorFormat depth)
 {
     this.pltt.Depth = depth;
     this.pltt.PaletteColors = palette;
     this.GetInfo();
 }
예제 #30
0
        /// <summary>
        /// Generate pixels, palette and update objects in frames.
        /// </summary>
        /// <param name="pixels">Pixels of frames.</param>
        /// <param name="palettes">Palettes of frames.</param>
        private void CreateData(out Pixel[] pixelsLin, out Pixel[] pixelsHori, out Color[][] palettes)
        {
            int tileSize = 128;
            int fullTileSize = (this.PaletteMode == PaletteMode.Palette16_16) ? tileSize * 2 : tileSize;
            int maxColors   = this.Format.MaxColors();
            int numPalettes = (maxColors <= 16) ? 16 : 1;

            // Create the ObjData. Quantizate images.
            List<Color[]> palettesList = new List<Color[]>();
            List<ObjectData> data = new List<ObjectData>();
            foreach (Tuple<Frame, EmguImage> frame in this.frameData) {
                EmguImage frameImg = frame.Item2;
                Obj[] objects = frame.Item1.GetObjects();

                foreach (Obj obj in objects) {
                    ObjectData objData = new ObjectData();
                    objData.Object = obj;

                    Rectangle area = obj.GetArea();
                    area.Offset(256, 128);
                    objData.Image = frameImg.Copy(area);

                    // Update object
                    objData.Object.Mode        = this.ObjectMode;
                    objData.Object.PaletteMode = this.PaletteMode;

                    // Quantizate
                    this.Quantization.Quantizate(objData.Image);
                    objData.PixelsLineal     = this.Quantization.GetPixels(PixelEncoding.Lineal);
                    objData.PixelsHorizontal = this.Quantization.GetPixels(PixelEncoding.HorizontalTiles);
                    objData.Palette = this.Quantization.Palette;
                    if (objData.Palette.Length > maxColors)
                        throw new FormatException(string.Format("The image has more than {0} colors", maxColors));

                    ManyFixedPaletteQuantization manyFixed = this.Quantization as ManyFixedPaletteQuantization;
                    if (this.OriginalPalettes != null && manyFixed != null)
                        objData.Object.PaletteIndex = (byte)manyFixed.SelectedPalette;

                    palettesList.Add(objData.Palette);

                    data.Add(objData);
                }
            }

            // Reduce palettes if necessary
            if (this.OriginalPalettes == null) {
                this.Reducer.Clear();
                this.Reducer.MaxColors = maxColors;
                this.Reducer.AddPaletteRange(palettesList.ToArray());
                this.Reducer.Reduce(numPalettes);
                palettes = this.Reducer.ReducedPalettes;

                // Approximate palettes removed
                for (int i = 0; i < data.Count; i++) {
                    int paletteIdx = this.Reducer.PaletteApproximation[i];
                    if (paletteIdx >= 0) {
                        // Quantizate again the image with the new palette
                        Color[] newPalette = palettes[paletteIdx];
                        FixedPaletteQuantization quantization = new FixedPaletteQuantization(newPalette);
                        quantization.Quantizate(data[i].Image);

                        // Get the pixel
                        data[i].PixelsLineal     = quantization.GetPixels(PixelEncoding.Lineal);
                        data[i].PixelsHorizontal = quantization.GetPixels(PixelEncoding.HorizontalTiles);
                    } else {
                        paletteIdx = (paletteIdx + 1) * -1;
                    }

                    // Update object
                    data[i].Object.PaletteIndex = (byte)paletteIdx;
                }
            } else {
                if (this.OriginalPalettes.Length > numPalettes)
                    throw new FormatException("More original palettes than allowed");

                palettes = this.OriginalPalettes;
            }

            List<Pixel> pixelLinList  = new List<Pixel>();
            List<Pixel> pixelHoriList = new List<Pixel>();
            for (int i = 0; i < data.Count; i++) {
                // Search the data into the array to ensure there is no duplicated tiles
                int tileNumber = SearchTile(pixelLinList, data[i].PixelsLineal, tileSize);
                data[i].Object.TileNumber = (ushort)tileNumber;

                // Add pixels to the list
                if (tileNumber == -1) {
                    data[i].Object.TileNumber = (ushort)(pixelLinList.Count / tileSize);
                    pixelLinList.AddRange(data[i].PixelsLineal);
                    pixelHoriList.AddRange(data[i].PixelsHorizontal);

                    // Pad to tilesize to increment at least one tilenumber next time
                    while (pixelLinList.Count % fullTileSize != 0)
                        pixelLinList.Add(new Pixel(0, 0, true));

                    while (pixelHoriList.Count % fullTileSize != 0)
                        pixelHoriList.Add(new Pixel(0, 0, true));
                }
            }

            pixelsLin  = pixelLinList.ToArray();
            pixelsHori = pixelHoriList.ToArray();
        }
예제 #31
0
파일: Image.cs 프로젝트: pleonex/ninoimager
 private static Color[] InfoToIndexedColors(uint[] colorInfo, Color[][] palettes, uint[] palIdx)
 {
     Color[] colors = new Color[colorInfo.Length];
     for (int i = 0; i < colorInfo.Length; i++)
         colors[i] = InfoToIndexedColor(colorInfo[i], palettes[palIdx[i]]);
     return colors;
 }
예제 #32
0
 public static double GetDistance(this Color c1, Color c2)
 {
     return Math.Sqrt(c1.GetDistanceSquared(c2));
 }
예제 #33
0
        public static Color[] ToBgr555Colors(this byte[] values)
        {
            if (values.Length % 2 != 0)
                throw new ArgumentException("Length must be even.");

            Color[] colors = new Color[values.Length / 2];
            for (int i = 0; i < colors.Length; i++) {
                colors[i] = BitConverter.ToUInt16(values, i*2).ToBgr555Color();
            }

            return colors;
        }
예제 #34
0
 public FixedPaletteQuantization(Color[] fixedPalette)
 {
     this.nearestNeighbour = new ExhaustivePaletteSearch();
     this.Palette = fixedPalette;
 }
예제 #35
0
        private static void SearchPalette(string packPath, string imgPath, int idx)
        {
            // Get new image
            EmguImage newImg = new EmguImage(imgPath);

            // Get original image
            Npck pack = new Npck(packPath);
            Btx0 texture = new Btx0(pack[0]);
            Image originalImg = texture.GetImage(idx);
            Pixel[] pixels = originalImg.GetPixels();

            // For each pixel, set palette color in the position given by original image
            Color[] palette = new Color[originalImg.Format.MaxColors()];
            for (int y = 0; y < newImg.Height; y++) {
                for (int x = 0; x < newImg.Width; x++) {
                    // Get target color
                    Color px = newImg[y, x];

                    // Get palette color index
                    uint index = pixels[y * newImg.Width + x].Info;

                    // If we have already set this color, and it does not match with
                    // this pixel... Error!
                    if (palette[index].Alpha != 0 && !palette[index].Equals(px)) {
                        Console.WriteLine("Can not find a valid color combination");
                        return;
                    }

                    // If the color has not been set, set it!
                    if (palette[index].Alpha == 0)
                        palette[index] = px;
                }
            }

            // Print palette
            Console.WriteLine("Palette found");
            string xmlColor = "          <Color red=\"{0}\" green=\"{1}\" blue=\"{2}\" />";
            foreach (Color c in palette)
                Console.WriteLine(xmlColor, c.Red, c.Green, c.Blue);
        }
예제 #36
0
        private static Difference[,] CalculateDistances(Color[][] palettes)
        {
            // Combination of each palette with each palette except with itself (diagonal)
            Difference[,] distances = new Difference[palettes.Length, palettes.Length];

            // Convert palettes to labcolor space to compute difference
            LabColor[][] labPalettes = new LabColor[palettes.Length][];
            for (int i = 0; i < palettes.Length; i++)
                labPalettes[i] = ColorConversion.ToLabPalette<Color>(palettes[i]);

            // Compute every possible difference
            for (int i = 0; i < palettes.Length; i++) {
                for (int j = 0; j < palettes.Length; j++) {
                    if (i == j)
                        continue;

                    distances[i, j] = new Difference();
                    distances[i, j].SrcPalette = i;
                    distances[i, j].DstPalette = j;
                    distances[i, j].Distance   = PaletteDistance.CalculateDistance(
                        labPalettes[i], labPalettes[j]);
                }
            }

            return distances;
        }
예제 #37
0
        private static void JoinPalettes(Color[] srcPalette, ref Color[] dstPalette)
        {
            List<Color> outputPalette = new List<Color>(dstPalette);
            foreach (Color c in srcPalette) {
                if (outputPalette.Contains(c))
                    continue;

                // Remove one null color (color to fill space) and add our color
                outputPalette.Remove(NullColor);
                outputPalette.Add(c);
            }

            dstPalette = outputPalette.ToArray();
        }
예제 #38
0
        private static int CountColorInPalette(Color[] palette)
        {
            int count = 0;
            foreach (Color c in palette)
                if (!c.Equals(NullColor))
                    count++;

            return count;
        }
예제 #39
0
 public void AddPaletteRange(Color[][] palettes)
 {
     this.palettes.AddRange(palettes);
 }
예제 #40
0
파일: Nclr.cs 프로젝트: pleonex/ninoimager
        private static Color[][] DividePalette(int numColors, int numPalettes, Color[] palette, ushort[] index = null)
        {
            if (index != null && index.Length != numPalettes)
                throw new ArgumentOutOfRangeException();

            Color[][] newPalettes;
            if (index != null && index.Length > 0)
                newPalettes = new Color[index.Max() + 1][];
            else
                newPalettes = new Color[numPalettes][];
            for (int i = 0; i < newPalettes.Length; i++)
                newPalettes[i] = new Color[0];

            // Set the right palette
              int totalColors = palette.Length;
            for (int i = 0; i < numPalettes; i++) {
                int idx = (index != null) ? index[i] : i;
                int copyColors = ((i + 1) * numColors < totalColors) ? numColors : totalColors - i * numColors;
                newPalettes[idx] = new Color[copyColors];
                Array.Copy(palette, i * numColors, newPalettes[idx], 0, copyColors);
            }

            return newPalettes;
        }
예제 #41
0
        private static void MultiImport(string baseDir, string outputDir,
                                        List <ImageInfo> importedList, string xml, bool filterDate)
        {
            if (string.IsNullOrEmpty(xml))
            {
                return;
            }

            XDocument doc = XDocument.Load(xml);

            foreach (XElement entry in doc.Root.Elements("Pack"))
            {
                // Get mode
                string mode = entry.Element("Mode").Value;

                // Get paths
                bool             existImages = true;
                List <string>    images      = new List <string>();
                List <ImageInfo> infos       = new List <ImageInfo>();
                foreach (XElement ximg in entry.Element("Images").Elements("Image"))
                {
                    string frame = (ximg.Attribute("frame") != null) ?
                                   "_" + ximg.Attribute("frame").Value : "";

                    ImageInfo info = new ImageInfo();
                    info.AbsoluteImage = Path.Combine(baseDir, ximg.Value) + frame + M + ".png";
                    info.Filename      = Path.GetFileNameWithoutExtension(ximg.Value);
                    info.PackExtension = (mode != "TextureWithPalette") ? ".n2d" : ".n3d";
                    info.RelativePath  = Path.GetDirectoryName(ximg.Value) + Path.DirectorySeparatorChar;
                    infos.Add(info);

                    images.Add(info.AbsoluteImage);

                    if (!File.Exists(info.AbsoluteImage))
                    {
                        existImages = false;
                        break;
                    }
                }

                // Import
                Console.Write("|-Importing {0,-45} | ", infos[0].RelativeImage);
                for (int i = 1; i < infos.Count; i++)
                {
                    Console.WriteLine();
                    Console.Write("            {0,-45} | ", infos[i].RelativeImage);
                }

                // Images still not translated
                if (!existImages)
                {
                    Console.WriteLine("Skipped: Images not found");
                    continue;
                }

                // If don't match the filter, skip
                if (filterDate)
                {
                    DateTime referenceDate = File.GetLastWriteTime(outputDir + infos[0].RelativeNewPack);
                    if (!images.Any(f => File.GetLastWriteTime(f) > referenceDate))
                    {
                        Console.WriteLine("Skipped: date filter");
                        continue;
                    }
                }

                Npck   originalPack = new Npck(outputDir + infos[0].RelativePack);
                Npck[] packs        = null;
                if (mode == "SharePalette")
                {
                    packs = NpckFactory.FromBackgroundImageSharePalette(images.ToArray(), originalPack);
                }
                else if (mode == "ChangePalette")
                {
                    packs = new Npck[1] {
                        NpckFactory.FromBackgroundImage(images[0], originalPack, true)
                    }
                }
                ;
                else if (mode == "ShareImage")
                {
                    packs = NpckFactory.FromBackgroundImageShareImage(images.ToArray(), originalPack);
                }
                else if (mode == "SharePaletteChangeDepth")
                {
                    packs = NpckFactory.FromBackgroundImageSharePaletteChangeDepth(images.ToArray(), originalPack, true);
                }
                else if (mode == "TextureWithPalette")
                {
                    // Get frames
                    string     frame  = entry.Element("Images").Elements("Image").First().Attribute("frame").Value;
                    List <int> frames = new List <int>()
                    {
                        Convert.ToInt32(frame)
                    };

                    // Create palette
                    XElement[] xcolors = entry.Element("Palette").Elements("Color").ToArray();
                    Color[]    colors  = new Color[xcolors.Length];
                    for (int i = 0; i < colors.Length; i++)
                    {
                        colors[i]       = new Color();
                        colors[i].Red   = Convert.ToInt32(xcolors[i].Attribute("red").Value);
                        colors[i].Green = Convert.ToInt32(xcolors[i].Attribute("green").Value);
                        colors[i].Blue  = Convert.ToInt32(xcolors[i].Attribute("blue").Value);
                    }
                    Palette palette = new Palette(colors);

                    // Generate pack file
                    packs    = new Npck[1];
                    packs[0] = NpckFactory.ChangeTextureImages(images.ToArray(), frames.ToArray(), palette, originalPack);
                }
                else
                {
                    throw new FormatException(string.Format("Unsopported mode \"{0}\"", mode));
                }

                // Write output
                originalPack.CloseAll();
                for (int i = 0; i < infos.Count; i++)
                {
                    packs[i].Write(outputDir + infos[i].RelativeNewPack);
                    packs[i].CloseAll();
                }

                importedList.AddRange(infos);
                Console.WriteLine("Successfully");
            }
        }
예제 #42
0
 public static void SetPixels(this EmguImage img, int x, int y, int width, int height, Color[] pixels)
 {
     img.SetPixels(new Rectangle(x, y, width, height), pixels);
 }
예제 #43
0
 public Palette(Color[][] palette)
 {
     this.SetPalette(palette);
 }
예제 #44
0
 public static Color[] ToArgbColors(this uint[] argb)
 {
     Color[] colors = new Color[argb.Length];
     for (int i = 0; i < argb.Length; i++)
         colors[i] = argb[i].ToArgbColor();
     return colors;
 }
예제 #45
0
 public static double GetDistance(this Color c1, Color c2)
 {
     return(Math.Sqrt(c1.GetDistanceSquared(c2)));
 }
예제 #46
0
 public void SetPalette(Color[] palette)
 {
     this.palette = new Color[1][];
     this.palette[0] = new Color[palette.Length];
     Array.Copy(palette, this.palette[0], palette.Length);
 }
예제 #47
0
 public static double GetDistanceSquared(this Color c1, Color c2)
 {
     return((c2.Red - c1.Red) * (c2.Red - c1.Red) +
            (c2.Green - c1.Green) * (c2.Green - c1.Green) +
            (c2.Blue - c1.Blue) * (c2.Blue - c1.Blue));
 }
예제 #48
0
 public static double GetDistanceSquared(this Color c1, Color c2)
 {
     return 	(c2.Red - c1.Red) * (c2.Red - c1.Red) +
         (c2.Green - c1.Green) * (c2.Green - c1.Green) +
         (c2.Blue - c1.Blue) * (c2.Blue - c1.Blue);
 }
예제 #49
0
        private static void MultiImport(string baseDir, string outputDir, 
			List<ImageInfo> importedList, string xml, bool filterDate)
        {
            if (string.IsNullOrEmpty(xml))
                return;

            XDocument doc = XDocument.Load(xml);
            foreach (XElement entry in doc.Root.Elements("Pack")) {
                // Get mode
                string mode = entry.Element("Mode").Value;

                // Get paths
                bool existImages = true;
                List<string> images   = new List<string>();
                List<ImageInfo> infos = new List<ImageInfo>();
                foreach (XElement ximg in entry.Element("Images").Elements("Image")) {
                    string frame = (ximg.Attribute("frame") != null) ?
                        "_" + ximg.Attribute("frame").Value : "" ;

                    ImageInfo info = new ImageInfo();
                    info.AbsoluteImage = Path.Combine(baseDir, ximg.Value) + frame + M + ".png";
                    info.Filename      = Path.GetFileNameWithoutExtension(ximg.Value);
                    info.PackExtension = (mode != "TextureWithPalette") ? ".n2d" : ".n3d";
                    info.RelativePath  = Path.GetDirectoryName(ximg.Value) + Path.DirectorySeparatorChar;
                    infos.Add(info);

                    images.Add(info.AbsoluteImage);

                    if (!File.Exists(info.AbsoluteImage)) {
                        existImages = false;
                        break;
                    }
                }

                // Import
                Console.Write("|-Importing {0,-45} | ", infos[0].RelativeImage);
                for (int i = 1; i < infos.Count; i++) {
                    Console.WriteLine();
                    Console.Write("            {0,-45} | ", infos[i].RelativeImage);
                }

                // Images still not translated
                if (!existImages) {
                    Console.WriteLine("Skipped: Images not found");
                    continue;
                }

                // If don't match the filter, skip
                if (filterDate) {
                    DateTime referenceDate = File.GetLastWriteTime(outputDir + infos[0].RelativeNewPack);
                    if (!images.Any(f => File.GetLastWriteTime(f) > referenceDate)) {
                        Console.WriteLine("Skipped: date filter");
                        continue;
                    }
                }

                Npck originalPack = new Npck(outputDir + infos[0].RelativePack);
                Npck[] packs = null;
                if (mode == "SharePalette")
                    packs = NpckFactory.FromBackgroundImageSharePalette(images.ToArray(), originalPack);
                else if (mode == "ChangePalette")
                    packs = new Npck[1] { NpckFactory.FromBackgroundImage(images[0], originalPack, true) };
                else if (mode == "ShareImage")
                    packs = NpckFactory.FromBackgroundImageShareImage(images.ToArray(), originalPack);
                else if (mode == "SharePaletteChangeDepth")
                    packs = NpckFactory.FromBackgroundImageSharePaletteChangeDepth(images.ToArray(), originalPack, true);
                else if (mode == "TextureWithPalette") {
                    // Get frames
                    string frame = entry.Element("Images").Elements("Image").First().Attribute("frame").Value;
                    List<int> frames = new List<int>() { Convert.ToInt32(frame) };

                    // Create palette
                    XElement[] xcolors = entry.Element("Palette").Elements("Color").ToArray();
                    Color[] colors = new Color[xcolors.Length];
                    for (int i = 0; i < colors.Length; i++) {
                        colors[i] = new Color();
                        colors[i].Red   = Convert.ToInt32(xcolors[i].Attribute("red").Value);
                        colors[i].Green = Convert.ToInt32(xcolors[i].Attribute("green").Value);
                        colors[i].Blue  = Convert.ToInt32(xcolors[i].Attribute("blue").Value);
                    }
                    Palette palette = new Palette(colors);

                    // Generate pack file
                    packs = new Npck[1];
                    packs[0] = NpckFactory.ChangeTextureImages(images.ToArray(), frames.ToArray(), palette, originalPack);
                } else
                    throw new FormatException(string.Format("Unsopported mode \"{0}\"", mode));

                // Write output
                originalPack.CloseAll();
                for (int i = 0; i < infos.Count; i++) {
                    packs[i].Write(outputDir + infos[i].RelativeNewPack);
                    packs[i].CloseAll();
                }

                importedList.AddRange(infos);
                Console.WriteLine("Successfully");
            }
        }
예제 #50
0
 public abstract double distance(Emgu.CV.Structure.Bgra color, IColorComparison comp, byte transparencyThreshold);
예제 #51
0
        private static void ExportTextureWithColors(string n3dPath, string outPath, string colors)
        {
            string name = Path.GetFileNameWithoutExtension(n3dPath);
            string path = Path.Combine(outPath, name);

            // Get texture file
            Npck pack = new Npck(n3dPath);
            Btx0 texture = new Btx0(pack[0]);

            // Parse colors
            string[] strColors = colors.Split(' ');
            Color[] newColors = new Color[strColors.Length];
            for (int i = 0; i < strColors.Length; i++) {
                int hexColor = Convert.ToInt32(strColors[i], 16);
                newColors[i] = new Color();
                newColors[i].Alpha = 255;
                newColors[i].Red   = (hexColor >> 00) & 0xFF;
                newColors[i].Green = (hexColor >> 08) & 0xFF;
                newColors[i].Blue  = (hexColor >> 16) & 0xFF;
            }

            // Create and export palette
            Palette palette = new Palette(newColors);
            palette.ToWinPaletteFormat(path + "_palGimp.pal", 0, true);
            palette.ToWinPaletteFormat(path + "_pal.pal", 0, false);
            palette.CreateBitmap(0).Save(path + "_pal.png");

            // For each image, set new palette and export it
            for (int i = 0; i < texture.NumTextures; i++)
                texture.CreateBitmap(i, palette).Save(path + "_" + i.ToString() + ".png");
        }
예제 #52
0
 public void SetPalette(Color[][] palette)
 {
     this.palette = new Color[palette.Length][];
     for (int i = 0; i < palette.Length; i++) {
         this.palette[i] = new Color[palette[i].Length];
         Array.Copy(palette[i], this.palette[i], palette[i].Length);
     }
 }
예제 #53
0
 public void AddPalette(Color[] palette)
 {
     this.palettes.Add(palette);
 }