Ejemplo n.º 1
0
        private void RenderTurkFile(String filename, String turkDir)
        {
            String[] lines = File.ReadAllLines(filename);
            foreach (String line in lines)
            {
                String[] fields = line.Split('|');
                String   pid    = fields[0];
                String[] colors = fields[3].Split('^');

                //render the template
                Bitmap template = GetFinalRendering(pid, new PaletteData());
                if (template != null)
                {
                    template.Save(Path.Combine(turkDir, pid + "_t.png"));

                    //render the candidate pattern
                    String      name = fields[1] + ".png";
                    PaletteData data = new PaletteData();
                    foreach (String color in colors)
                    {
                        int[] cfields = color.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).Select <String, int>(s => ((int)(Math.Round(double.Parse(s) * 255)))).ToArray <int>();
                        data.colors.Add(Color.FromArgb(cfields[0], cfields[1], cfields[2]));
                    }
                    Bitmap cand = GetFinalRendering(pid, data);
                    cand.Save(Path.Combine(turkDir, name));

                    cand.Dispose();
                    template.Dispose();
                }
            }
        }
Ejemplo n.º 2
0
        private Dictionary <String, List <PaletteData> > LoadFilePalettes(String file)
        {
            //load art palettes
            String[] lines = File.ReadAllLines(file);

            Dictionary <String, List <PaletteData> > plist = new Dictionary <String, List <PaletteData> >();

            for (int i = 1; i < lines.Count(); i++)
            {
                String      line   = lines[i];
                String[]    fields = line.Replace("\"", "").Split('\t');
                PaletteData data   = new PaletteData();
                data.id        = Int32.Parse(fields[0]);
                data.workerNum = Int32.Parse(fields[1]);
                String   key    = fields[2];
                String[] colors = fields[3].Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                foreach (String s in colors)
                {
                    String[] comp = s.Split(',');
                    Color    c    = Color.FromArgb(Int32.Parse(comp[0]), Int32.Parse(comp[1]), Int32.Parse(comp[2]));
                    CIELAB   l    = Util.RGBtoLAB(c);
                    data.colors.Add(c);
                    data.lab.Add(l);
                }
                if (!plist.ContainsKey(key))
                {
                    plist.Add(key, new List <PaletteData>());
                }
                plist[key].Add(data);
            }
            return(plist);
        }
Ejemplo n.º 3
0
    protected virtual PaletteData drawSizeButtons(PaletteData data)
    {
        GUILayout.Space(10);

        Rect buttonRect = EditorGUILayout.BeginHorizontal();

        EditorGUILayout.LabelField("Change the size of the Palette: ");


        if (GUI.Button(new Rect(Screen.width - 50 - 32 - buttonMarginBetween, buttonRect.y, 32, 32), new GUIContent(plusTex, "Add Color"), EditorStyles.miniButtonRight))
        {
            data.setSize(data.colors.Length + 1);
        }

        if (GUI.Button(new Rect(Screen.width - 50, buttonRect.y, 32, 32), new GUIContent(minusTex, "Remove last Color"), EditorStyles.miniButton))
        {
            data.setSize(data.colors.Length - 1);
        }

        EditorGUILayout.EndHorizontal();

        GUILayout.Space(10);

        return(data);
    }
Ejemplo n.º 4
0
    public void Create(Texture2D l, Texture2D c, PaletteData p)
    {
        this.lineContourText = l;
        this.paletteData     = p;
        this.colorSourceText = c;
        Color[] pixels = this.colorSourceText.GetPixels();
        byte[]  array  = new byte[pixels.Length];
        if (this.paintEngine == null)
        {
            this.paintEngine = new AdvancedMobilePaint();
        }
        this.paintEngine.pixels    = new byte[this.colorSourceText.width * this.colorSourceText.height * 4];
        this.paintEngine.texHeight = this.colorSourceText.height;
        this.paintEngine.texWidth  = this.colorSourceText.width;
        this.paintEngine.source    = array;
        this.drawText = new Texture2D(this.colorSourceText.width, this.colorSourceText.height, TextureFormat.RGBA32, false);
        this.drawText.LoadRawTextureData(this.paintEngine.pixels);
        this.drawText.filterMode = FilterMode.Bilinear;
        this.drawText.wrapMode   = TextureWrapMode.Clamp;
        this.drawText.Apply();
        float num = 0.06f;

        for (int i = 0; i < pixels.Length; i++)
        {
            if (pixels[i].r < num && pixels[i].g < num && pixels[i].b < num)
            {
                array[i] = byte.MaxValue;
            }
            else
            {
                array[i] = 0;
            }
        }
    }
Ejemplo n.º 5
0
        private void extractTheme_Click(object sender, EventArgs e)
        {
            //Use the Palette Extractor to extract the theme
            PaletteExtractor extractor = new PaletteExtractor(dir, weightsDir, json);

            String[] files   = Directory.GetFiles(dir, "*.png");
            String   outfile = dir + "\\palettes.tsv";
            String   headers = "pid\tid\timage\tcolors\tnumColors\tlog\n";

            File.WriteAllText(outfile, "");
            File.AppendAllText(outfile, headers);
            int count = 0;

            foreach (String f in files)
            {
                count++;
                String basename = f.Replace(dir + "\\", "");

                //The saliency pattern "_Judd" is just an additional annotation after the image filename if it exists
                //i.e. if the image filename is A.png, the saliency map filename is A_Judd.png
                PaletteData data = extractor.HillClimbPalette(basename, "_Judd", true);

                //save to file
                String colorString = data.ToString();
                File.AppendAllText(outfile, count + "\t-1\t" + basename + "\t" + colorString + "\t5\t\n");
            }
        }
Ejemplo n.º 6
0
        public Bitmap Decode(RoomBlock roomBlock, int objectIndex, int imageIndex)
        {
            var obj = roomBlock.GetOBIMs()[objectIndex];

            if (obj.GetIMxx()[imageIndex].GetSMAP() == null)
            {
                return(new Bitmap(1, 1));
            }

            var IMHD = obj.GetIMHD();

            _width        = IMHD.Width;
            _height       = IMHD.Height;
            _transparency = roomBlock.GetTRNS().Value;
            _strips       = obj.GetIMxx()[imageIndex].GetSMAP().Strips;

            if (PaletteIndex == 0)
            {
                _pallete = roomBlock.GetDefaultPalette();
            }
            else
            {
                _pallete = roomBlock.GetPALS().GetWRAP().GetAPALs()[PaletteIndex];
            }

            Decode();

            return(_resultBitmap);
        }
Ejemplo n.º 7
0
        public Bitmap Decode(RoomBlock roomBlock, int objectIndex, int imageIndex)
        {
            ObjectImage obj = roomBlock.GetOBIMs()[objectIndex];

            if (obj.GetIMxx()[imageIndex].GetBOMP() == null)
            {
                return(new Bitmap(1, 1));
            }

            var IMHD = obj.GetIMHD();

            _width     = IMHD.Width;
            _height    = IMHD.Height;
            _imageData = obj.GetIMxx()[imageIndex].GetBOMP();

            if (PaletteIndex == 0)
            {
                _pallete = roomBlock.GetDefaultPalette();
            }
            else
            {
                _pallete = roomBlock.GetPALS().GetWRAP().GetAPALs()[PaletteIndex];
            }

            Decode();

            return(_resultBitmap);
        }
Ejemplo n.º 8
0
 public void Init(PaletteData pd)
 {
     for (int i = 0; i < pd.entities.Length; i++)
     {
         this.TotalPieces += pd.entities[i].indexes.Length;
         this.progress.Add(pd.entities[i].indexes.Length);
     }
 }
Ejemplo n.º 9
0
    protected virtual PaletteData drawColorsAndPercentages(PaletteData data)
    {
        GUILayoutUtility.GetRect(Screen.width, 10);

        adjustPCTBefore = GUILayout.Toggle(adjustPCTBefore, " adjust percentage to the left");

        Rect colorChangerRect = GUILayoutUtility.GetRect(Screen.width, data.colors.Length * colorChangerRowHeight);

        colorChangerRect.x     += colorChangeLeftMargin;
        colorChangerRect.width -= colorChangeRightMargin;

        GUILayoutUtility.GetRect(Screen.width, 10);

        float startY = colorChangerRect.y + 10;

        for (int i = 0; i < data.colors.Length; i++)
        {
            // draw a little preview of the current color
            Rect colRect = new Rect(colorChangerRect.x, startY,
                                    150, colorChangerRowHeight);

            Color currentColor = data.colors [i];
            Color newColor     = EditorGUI.ColorField(colRect, currentColor);

            string currentHex = JSONPersistor.ColorToHex(currentColor);

            Rect hexRect = new Rect(colorChangerRect.x + colRect.width + colorChangeMarginBetween,
                                    startY, hexFieldWidth, colorChangerRowHeight);

            string newHex = EditorGUI.TextField(hexRect, currentHex);

            if (!currentHex.Equals(newHex))
            {
                data.colors [i] = JSONPersistor.HexToColor(newHex);
            }
            else if (!currentColor.ToString().Equals(newColor.ToString()))
            {
                data.colors [i] = newColor;
                data.alphas [i] = newColor.a;
            }

            float currentPct = data.percentages [i];
            float maxPct     = 1.0f - (data.percentages.Length - 1) * this.minPct;
            //Debug.Log ("max % " + maxPct);

            Rect silderRect = new Rect(colorChangerRect.x + colRect.width + colorChangeMarginBetween + hexRect.width + colorChangeMarginBetween, startY,
                                       colorChangerRect.width - colorChangeMarginBetween - colRect.width - colorChangeMarginBetween - hexRect.width,
                                       colorChangerRowHeight);

            float newPct = EditorGUI.Slider(silderRect, currentPct, this.minPct, maxPct);
            data = adjustPct(data, i, newPct, currentPct, maxPct);


            startY += colorChangerRowHeight;
        }

        return(data);
    }
Ejemplo n.º 10
0
    private void PrepareMandala()
    {
        this.fType             = FloodTest.FillType.Fast;
        this.lineContourText   = this.LoadImage(FloodTest.IMG_NAME_INDEX.ToString());
        this.sourceImg.texture = this.lineContourText;
        this.colorSourceText   = this.LoadImage(FloodTest.IMG_NAME_INDEX + "ccc");
        this.pixels            = this.colorSourceText.GetPixels();
        this.sourceAlpha       = new byte[this.pixels.Length];
        if (this.paintEngine == null)
        {
            this.paintEngine = new AdvancedMobilePaint();
        }
        this.paintEngine.pixels    = new byte[this.colorSourceText.width * this.colorSourceText.height * 4];
        this.paintEngine.texHeight = this.colorSourceText.height;
        this.paintEngine.texWidth  = this.colorSourceText.width;
        this.paintEngine.source    = this.sourceAlpha;
        this.drawText = new Texture2D(this.colorSourceText.width, this.colorSourceText.height, TextureFormat.RGBA32, false);
        this.drawText.LoadRawTextureData(this.paintEngine.pixels);
        this.drawText.filterMode = FilterMode.Point;
        this.drawText.Apply();
        this.imageRect       = this.sourceImg.rectTransform.rect;
        this.drawImg.texture = this.drawText;
        float num;

        if (FloodTest.IMG_NAME_INDEX < 104)
        {
            num = 0.09f;
        }
        else
        {
            num = 0.02f;
        }
        for (int i = 0; i < this.pixels.Length; i++)
        {
            if (this.pixels[i].r < num && this.pixels[i].g < num && this.pixels[i].b < num)
            {
                this.sourceAlpha[i] = byte.MaxValue;
            }
            else
            {
                this.sourceAlpha[i] = 0;
            }
        }
        string      value       = FileHelper.LoadTextAssetResource(FloodTest.IMG_NAME_INDEX + "t");
        PaletteData paletteData = JsonConvert.DeserializeObject <PaletteData>(value);

        for (int j = 0; j < paletteData.entities.Length; j++)
        {
            PaletteEntity paletteEntity = paletteData.entities[j];
            for (int k = 0; k < paletteEntity.indexes.Length; k++)
            {
                Point p = default(Point);
                p.i = Mathf.FloorToInt((float)paletteEntity.indexes[k] / (float)this.colorSourceText.width);
                p.j = paletteEntity.indexes[k] - p.i * this.colorSourceText.width;
                this.CreateNumView(this.TextureToCanvas(p), j);
            }
        }
    }
Ejemplo n.º 11
0
        private CIELAB[,] AverageRecolor(CIELAB[,] image, PaletteData palette)
        {
            int width  = image.GetLength(0);
            int height = image.GetLength(1);

            CIELAB[,] result = new CIELAB[width, height];

            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < height; j++)
                {
                    double[] scores = new double[palette.colors.Count()];

                    //check if the color is in the palette
                    CIELAB color = image[i, j];
                    if (palette.lab.Contains(color))
                    {
                        result[i, j] = color;
                        continue;
                    }

                    //otherwise, find the best color
                    for (int dx = -1; dx <= 1; dx++)
                    {
                        for (int dy = -1; dy <= 1; dy++)
                        {
                            int    x      = i + dx;
                            int    y      = j + dy;
                            double weight = (dx == 0 && dy == 0)? 4:1;
                            if (Util.InBounds(x, y, width, height))
                            {
                                for (int c = 0; c < palette.colors.Count(); c++)
                                {
                                    scores[c] += weight * image[x, y].SqDist(palette.lab[c]);
                                }
                            }
                        }
                    }

                    //pick the color with the min score
                    double minScore = Double.PositiveInfinity;
                    int    bestIdx  = 0;
                    for (int c = 0; c < palette.colors.Count(); c++)
                    {
                        if (scores[c] < minScore)
                        {
                            minScore = scores[c];
                            bestIdx  = c;
                        }
                    }

                    result[i, j] = palette.lab[bestIdx];
                }
            }

            return(result);
        }
Ejemplo n.º 12
0
        void AddNewPalette(CodedPalette newPalette)
        {
            var paletteData = new PaletteData(newPalette);

            AllPalettes.Add(paletteData);
            gridViewPalettes.CurrentCell = gridViewPalettes.Rows[AllPalettes.IndexOf(paletteData)].Cells[0];

            HasChanges = true;
        }
Ejemplo n.º 13
0
    public void Create(Texture2D l, PaletteData p, bool writeData = true)
    {
        this.paletteData = p;
        this.lineTex     = l;
        Color[] pixels = this.lineTex.GetPixels();
        short[] array  = new short[pixels.Length];
        this.paintEngine           = new ChopMobilePaint();
        this.paintEngine.pixels    = new byte[this.lineTex.width * this.lineTex.height * 4];
        this.paintEngine.texHeight = this.lineTex.height;
        this.paintEngine.texWidth  = this.lineTex.width;
        this.paintEngine.source    = array;
        this.paintEngine.zones     = new List <List <int> >();
        this.drawText            = new Texture2D(this.lineTex.width, this.lineTex.height, TextureFormat.RGBA32, false);
        this.drawText.filterMode = FilterMode.Bilinear;
        this.drawText.wrapMode   = TextureWrapMode.Clamp;
        for (int i = 0; i < pixels.Length; i++)
        {
            if (pixels[i].a >= 0.99f)
            {
                array[i] = short.MaxValue;
            }
            else
            {
                array[i] = this.emptyPixelTag;
            }
        }
        this.paintEngine.paintColor = Color.black;
        ChopFillAlgorithm.FindAndFillId(this.paintEngine, this.paintEngine.pixels, short.MaxValue);
        if (writeData)
        {
            this.drawText.LoadRawTextureData(this.paintEngine.pixels);
            this.drawText.Apply();
        }
        PaletteData paletteData = p;
        short       num         = 0;

        for (int j = 0; j < paletteData.entities.Length; j++)
        {
            for (int k = 0; k < paletteData.entities[j].indexes.Length; k++)
            {
                Point      point = this.paintEngine.TextureArrayIndexToMatrix(paletteData.entities[j].indexes[k]);
                List <int> list  = ChopFillAlgorithm.MarkArea(point.j, point.i, this.paintEngine, this.emptyPixelTag, num);
                if (list != null && list.Count > 0)
                {
                    this.paintedMap.Add(false);
                    this.colorMap.Add(j);
                    this.paintEngine.zones.Add(list);
                    num += 1;
                }
                else
                {
                    UnityEngine.Debug.Log("Error marking area");
                }
            }
        }
    }
Ejemplo n.º 14
0
        private void SavePaletteToImage(String dir, String key, String filename, PaletteData data)
        {
            int colorSize = 100;
            int numColors = data.colors.Count();
            int gridWidth = 10;
            int padding   = 20;

            int imageSize = 500;

            Bitmap image = new Bitmap(Image.FromFile(dir + "\\" + key));

            int imageWidth  = imageSize;
            int imageHeight = imageSize;

            if (image.Width > image.Height)
            {
                imageHeight = (int)Math.Round(imageSize / (double)image.Width * image.Height);
            }
            else
            {
                imageWidth = (int)Math.Round(imageSize / (double)image.Height * image.Width);
            }

            int width  = Math.Max(colorSize * Math.Min(gridWidth, numColors), imageSize) + 2 * padding;
            int height = imageHeight + 3 * padding + colorSize * (int)(Math.Ceiling(numColors / (double)gridWidth));

            Bitmap   bitmap = new Bitmap(width, height);
            Graphics g      = Graphics.FromImage(bitmap);


            //fill with black
            g.FillRectangle(new SolidBrush(Color.Black), 0, 0, bitmap.Width, bitmap.Height);


            //draw image
            g.DrawImage(image, padding, padding, imageWidth, imageHeight);

            //draw out the clusters
            for (int i = 0; i < numColors; i++)
            {
                int row = (int)Math.Floor(i / (double)gridWidth);
                int col = i - row * gridWidth;
                Pen pen = new Pen(data.colors[i]);
                g.FillRectangle(pen.Brush, col * colorSize + padding, imageHeight + 2 * padding + row * colorSize, colorSize - padding, colorSize - padding);

                double brightness = pen.Color.GetBrightness();
                Brush  brush      = new SolidBrush(Color.White);
                if (brightness > 0.5)
                {
                    brush = new SolidBrush(Color.Black);
                }
            }

            bitmap.Save(filename);
        }
Ejemplo n.º 15
0
    public bool Create(PictureData picData)
    {
        this.timeFromLastAction = DateTime.Now;
        Texture2D   texture2D = null;
        Texture2D   c         = null;
        PaletteData p         = default(PaletteData);

        this.fillType = picData.FillType;
        if (picData.picType == PictureType.System)
        {
            if (this.Error != null)
            {
                this.Error(Gameboard.LoadError.Unknown);
            }
            return(false);
        }
        if (picData.picType == PictureType.Local)
        {
            try
            {
                texture2D          = FileHelper.LoadTextureFromFile(picData.LineArt);
                texture2D.wrapMode = TextureWrapMode.Clamp;
                if (this.fillType == FillAlgorithm.Flood)
                {
                    c = FileHelper.LoadTextureFromFile(picData.ColorMap);
                }
                string json = FileHelper.LoadTextFromFile(picData.Palette);
                p = JsonUtility.FromJson <PaletteData>(json);
            }
            catch (Exception ex)
            {
                if (this.Error != null)
                {
                    this.Error(Gameboard.LoadError.FileMissing);
                    UnityEngine.Debug.Log(ex.ToString());
                }
                return(false);
            }
        }
        this.Create(texture2D, c, p);
        if (picData.HasSave)
        {
            PictureSaveData pictureSaveData = SharedData.Instance.GetSave(picData);
            if (pictureSaveData != null && pictureSaveData.steps != null)
            {
                this.LoadSave(pictureSaveData.steps);
                if (this.pictureSaveData != null)
                {
                    this.pictureSaveData.AddTimeSpent(pictureSaveData.timeSpent);
                    this.pictureSaveData.hintsUsed = pictureSaveData.hintsUsed;
                }
            }
        }
        return(true);
    }
    protected void drawAllPalettes()
    {
        GUILayout.Space(15);
        IDictionary <string, PaletteData> changeKeys = new Dictionary <string, PaletteData> ();

        int i = 0;

        if (this.showPalettes != null)
        {
            if (this.showPalettes.Length != myCollection.collectionData.palettes.Count)
            {
                changeShowPalette(myCollection.collectionData.palettes.Count);
            }

            foreach (KeyValuePair <string, PaletteData> kvp in myCollection.collectionData.palettes)
            {
                this.showPalettes [i] = EditorGUILayout.Foldout(this.showPalettes [i], kvp.Key + " ColorPalette");

                if (this.showPalettes [i])
                {
                    //				myCollection.collectionData.palettes [kvp.Key] =
                    PaletteData changeData = base.drawColorPalette(kvp.Value);
                    if (changeData.name != kvp.Key)
                    {
                        //Debug.Log ("name change: " + changeData.name);
                        changeKeys.Add(kvp.Key, changeData);
                    }
                    //myCollection.collectionData.palettes [kvp.Key] =
                    base.drawColorsAndPercentages(kvp.Value);
                    //myCollection.collectionData.palettes [kvp.Key] =
                    base.drawSizeButtons(kvp.Value);
                }

                i++;
            }

            if (changeKeys.Count > 0)
            {
                foreach (KeyValuePair <string, PaletteData> kvp in changeKeys)
                {
                    if (myCollection.collectionData.palettes.ContainsKey(kvp.Key))
                    {
                        //Debug.Log ("remove " + kvp.Key + " add " + kvp.Value.name);
                        myCollection.collectionData.palettes.Remove(kvp.Key);
                        myCollection.collectionData.palettes.Add(kvp.Value.name, kvp.Value);
                    }
                }
            }

/*				} else {
 *                                              Debug.Log ("showPalettes " + this.showPalettes.Length + " palettes " + myCollection.collectionData.palettes.Count);
 */
        }
    }
Ejemplo n.º 17
0
        //Test the quantization, connected components on different color layers, and output the descriptor
        private void OutputPatterns_Click(object sender, RoutedEventArgs e)
        {
            //Create output directories
            Directory.CreateDirectory(outdir + "\\cc\\");
            Directory.CreateDirectory(outdir + "\\quantized\\");
            Directory.CreateDirectory(outdir + "\\mesh\\");

            //read in the patterns and save out their layers
            String[]           files    = System.IO.Directory.GetFiles(System.IO.Path.Combine(imagedir));
            List <PatternItem> patterns = PatternIO.GetPatterns(imagedir);

            foreach (PatternItem p in patterns)
            {
                Bitmap image    = new Bitmap(p.FullPath);
                String basename = p.Name;

                //TODO: sometimes keys are not found in patterns.csv...will need to look into recovering missing info. For now, just ignore those patterns
                if (!palettes.ContainsKey(basename))
                {
                    continue;
                }

                PaletteData palette = palettes[basename];

                ColorTemplate template = new ColorTemplate(image, palette);

                //output the template descriptor
                SegmentMesh mesh = new SegmentMesh(template);
                PatternIO.SaveMesh(mesh, p, Path.Combine(outdir, "mesh"));

                if (outputDebugImages)
                {
                    Bitmap result = template.DebugQuantization();
                    PatternIO.SavePattern(result, p, Path.Combine(outdir, "quantized"), "_quantized");
                    PatternIO.SavePattern(result, p, Path.Combine(outdir, "quantized"), "_original");

                    //save the connected components
                    UnionFind <Color> uf = new UnionFind <Color>((a, b) => (a.GetHashCode() == b.GetHashCode()));
                    Color[,] resultArray = Util.BitmapToArray(result);
                    int[,] cc            = uf.ConnectedComponentsNoiseRemoval(resultArray);

                    int numColors = palette.colors.Count();
                    for (int i = 0; i < numColors; i++)
                    {
                        Bitmap debug = uf.RenderComponents(cc, resultArray, palette.colors[i]);
                        PatternIO.SavePattern(debug, p, Path.Combine(outdir, "cc"), "_" + i);
                        debug.Dispose();
                    }
                    result.Dispose();
                }
                image.Dispose();
            }
        }
Ejemplo n.º 18
0
        public ColorTemplate(Bitmap image, Segmentation seg, PaletteData palette)
        {
            slots           = seg; //TODO: need to copy the segmentation?
            originalPalette = new PaletteData(palette);

            int width  = image.Width;
            int height = image.Height;

            template = new CIELAB[width, height];

            //initialize the template
            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < height; j++)
                {
                    template[i, j] = Util.RGBtoLAB(image.GetPixel(i, j));
                }
            }

            segToColor = new int[seg.numSegments];

            //map each segment to the closest palette color, based on its mean color
            //TODO: if two adjacent segments have the same mean color, we could merge them...
            for (int i = 0; i < seg.numSegments; i++)
            {
                CIELAB lab       = seg.segToMeanColor[i];
                int    bestColor = -1;
                double bestDist  = Double.PositiveInfinity;
                for (int j = 0; j < palette.lab.Count(); j++)
                {
                    double dist = palette.lab[j].SqDist(lab);

                    if (dist < bestDist)
                    {
                        bestDist  = dist;
                        bestColor = j;
                    }
                }
                segToColor[i] = bestColor;
            }

            //subtract the mean color from the template
            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < height; j++)
                {
                    int coloridx = segToColor[slots.assignments[i, j]];
                    template[i, j] -= palette.lab[coloridx];
                    //template[i, j] /= palette.lab[coloridx];
                }
            }
        }
Ejemplo n.º 19
0
        public override void SetAndRefreshData(Structures.BlockBase blockBase)
        {
            base.SetAndRefreshData(blockBase);
            _paletteData = (PaletteData)blockBase;

            for (int i = 0; i < 255; i++)
            {
                Color backColor = _paletteData.Colors[i];
                PaletteTable.Controls[i].BackColor = backColor;
                ((PaletteColor)PaletteTable.Controls[i]).ColorChanged += (sender, index, color) => _paletteData.Colors[index] = color;

                toolTip1.SetToolTip(PaletteTable.Controls[i], string.Format("R: {0}, G:{1}, B:{2}", backColor.R, backColor.G, backColor.B));
            }
        }
Ejemplo n.º 20
0
 public void Init(AdvancedMobilePaint paintData, PaletteData data, Texture2D drawTexture)
 {
     this.drawImg.gameObject.SetActive(true);
     this.pd                        = data;
     this.paintEngine               = paintData;
     this.highlightEngine           = new AdvancedMobilePaint();
     this.highlightEngine.pixels    = new byte[this.paintEngine.pixels.Length];
     this.highlightEngine.source    = this.paintEngine.source;
     this.highlightEngine.texWidth  = this.paintEngine.texWidth;
     this.highlightEngine.texHeight = this.paintEngine.texHeight;
     this.drawText                  = new Texture2D(drawTexture.width, drawTexture.height, TextureFormat.RGBA32, false);
     this.drawText.LoadRawTextureData(this.highlightEngine.pixels);
     this.drawText.Apply();
     this.drawImg.texture = this.drawText;
 }
Ejemplo n.º 21
0
        public void Encode(RoomBlock roomBlock, Costume costume, int frameIndex, Bitmap imageToEncode)
        {
            _costume       = costume;
            _pictureData   = costume.Pictures[frameIndex];
            _imageToEncode = imageToEncode;
            if (PaletteIndex == 0)
            {
                _palette = roomBlock.GetDefaultPalette();
            }
            else
            {
                _palette = roomBlock.GetPALS().GetWRAP().GetAPALs()[PaletteIndex];
            }

            Encode();
        }
Ejemplo n.º 22
0
        public ColorTemplate(Bitmap image, PaletteData palette)
        {
            //create the segmentation based on the palette
            //TODO: There's a problem that sometimes a palette color won't appear in the image (perhaps due to color blending), and so the slot will have no pixels associated with it
            int width  = image.Width;
            int height = image.Height;

            slots      = new Segmentation(palette.colors.Count(), width, height);
            segToColor = new int[slots.numSegments];

            template = new CIELAB[width, height];

            CIELAB[,] recolored = ModeRecolor(Util.Map <Color, CIELAB>(Util.BitmapToArray(image), c => Util.RGBtoLAB(c)), palette);

            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < height; j++)
                {
                    template[i, j] = new CIELAB();
                    int    bestIdx  = -1;
                    CIELAB lab      = recolored[i, j];
                    double bestDist = Double.PositiveInfinity;

                    for (int c = 0; c < palette.lab.Count(); c++)
                    {
                        double dist = palette.lab[c].SqDist(lab);
                        if (dist < bestDist)
                        {
                            bestDist = dist;
                            bestIdx  = c;

                            if (dist < 0.00001)
                            {
                                break;
                            }
                        }
                    }

                    slots.assignments[i, j] = bestIdx;
                    slots.counts[bestIdx]++;
                    segToColor[bestIdx] = bestIdx;
                }
            }

            originalPalette = new PaletteData(palette);
        }
Ejemplo n.º 23
0
        private void SaveToDisk_Click(object sender, EventArgs e)
        {
            var dlg = new SaveFileDialog()
            {
                Filter = "PNG Files|*.png"
            };
            var result = dlg.ShowDialog();

            if (result == DialogResult.Cancel)
            {
                return;
            }

            int[]  usedPalleteIndexes;
            Bitmap background = GenericDecodeImage(out usedPalleteIndexes);

            //EncoderParameters parameters = new EncoderParameters();
            //var x = new System.Drawing.Imaging.Encoder(new Guid("66087055-ad66-4c7c-9a18-38a2310b8337"));
            //parameters.Param[0] = new EncoderParameter(x, 8);
            if (Export8Bits.Checked)
            {
                var convert = new ImageDepthConversor();
                if (_imageType == ImageType.Costume)
                {
                    var c = new List <Color>();
                    for (int i = 0; i < 256; i++)
                    {
                        c.Add(Color.Black);
                    }

                    PaletteData defaultPallete = _roomBlock.GetDefaultPalette();
                    for (int i = 0; i < _costume.Palette.Count; i++)
                    {
                        c[i] = defaultPallete.Colors[_costume.Palette[i]];
                    }
                    background = convert.CopyToBpp(background, 8, c.ToArray());
                }
                else
                {
                    background = convert.CopyToBpp(background, 8, _roomBlock.GetDefaultPalette().Colors);
                }
            }

            background.Save(dlg.FileName, ImageFormat.Png);
            File.WriteAllText(dlg.FileName + ".idx", string.Join(";", usedPalleteIndexes));
        }
Ejemplo n.º 24
0
        public Bitmap SolidColor(PaletteData palette, int[] slotToColor)
        {
            int    width  = Width();
            int    height = Height();
            Bitmap result = new Bitmap(width, height);

            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < height; j++)
                {
                    CIELAB lab = palette.lab[slotToColor[slots.assignments[i, j]]];
                    result.SetPixel(i, j, Util.LABtoRGB(lab));
                }
            }

            return(result);
        }
Ejemplo n.º 25
0
        public Bitmap Decode(RoomBlock roomBlock, Costume costume, int frameIndex)
        {
            _pictureData = costume.Pictures[frameIndex];
            _costume     = costume;

            if (PaletteIndex == 0)
            {
                _palette = roomBlock.GetDefaultPalette();
            }
            else
            {
                _palette = roomBlock.GetPALS().GetWRAP().GetAPALs()[PaletteIndex];
            }

            Decode();

            return(_resultBitmap);
        }
Ejemplo n.º 26
0
        public void Encode(RoomBlock blockToEncode, Bitmap imageToEncode)
        {
            _imageToEncode = imageToEncode;
            var RMHD = blockToEncode.GetRMHD();

            _width        = RMHD.Width;
            _height       = RMHD.Height;
            _transparency = blockToEncode.GetTRNS().Value;
            _strips       = blockToEncode.GetRMIM().GetIM00().GetSMAP();
            if (PaletteIndex == 0)
            {
                _pallete = blockToEncode.GetDefaultPalette();
            }
            else
            {
                _pallete = blockToEncode.GetPALS().GetWRAP().GetAPALs()[PaletteIndex];
            }

            Encode();
        }
Ejemplo n.º 27
0
        public void Encode(RoomBlock blockToEncode, Bitmap imageToEncode)
        {
            _imageToEncode = imageToEncode;
            RoomHeader RMHD = blockToEncode.GetRMHD();

            _width     = RMHD.Width;
            _height    = RMHD.Height;
            _imageBomp = blockToEncode.GetRMIM().GetIM00().GetBOMP();

            if (PaletteIndex == 0)
            {
                _pallete = blockToEncode.GetDefaultPalette();
            }
            else
            {
                _pallete = blockToEncode.GetPALS().GetWRAP().GetAPALs()[PaletteIndex];
            }

            Encode();
        }
Ejemplo n.º 28
0
        public void SetAndRefreshData(PaletteData paletteData, int paletteIndex)
        {
            for (int i = 0; i < 255; i++)
            {
                Color backColor = paletteData.Colors[i];

                PaletteTable.Controls[i].BackColor = backColor;
                ((PaletteColor)PaletteTable.Controls[i]).Selected = i == paletteIndex;
                PaletteTable.Controls[i].Click += (sender, args) =>
                {
                    foreach (var item in PaletteTable.Controls.OfType <PaletteColor>())
                    {
                        item.Selected = false;
                    }
                    ((PaletteColor)sender).Selected = true;
                };

                toolTip1.SetToolTip(PaletteTable.Controls[i], string.Format("R: {0}, G:{1}, B:{2}", backColor.R, backColor.G, backColor.B));
            }
        }
Ejemplo n.º 29
0
    protected virtual PaletteData adjustPct(PaletteData data, int i, float newPct, float currentPct, float maxPct)
    {
        if (newPct < this.minPct)
        {
            newPct = this.minPct;
        }

        if (newPct > maxPct)
        {
            newPct = maxPct;
        }

        if (newPct != currentPct)
        {
            //if (adjustNeighborPCT (i, currentPct - newPct)) {

            data = adjustNeighborPCT(data, i, currentPct - newPct);
            data.percentages [i] = newPct;

            // changes been made to neighbors, check if totalPcts is still 1 -> 100%
            float totalPcts = data.getTotalPct();

            if (totalPcts >= 1f)
            {
                float rounding = totalPcts - 1f;
                if (rounding > 0)
                {
                    //Debug.Log ("rounding " + newPct + " minus " + rounding + " to " + (newPct - rounding));
                    // always cut the last for the rounding!
                    data.percentages [data.percentages.Length - 1] -= rounding;
                }
                else if (rounding < 0)
                {
                    data.percentages [data.percentages.Length - 1] += rounding;
                }
            }
        }

        return(data);
    }
Ejemplo n.º 30
0
    private void JsonTest()
    {
        UnityEngine.Debug.Log(JsonConvert.DeserializeObject <PaletteData>(FileHelper.LoadTextFromFile("example.txt")).entities[0].color);
        PaletteData paletteData = default(PaletteData);

        paletteData.entities            = new PaletteEntity[3];
        paletteData.entities[0]         = default(PaletteEntity);
        paletteData.entities[0].color   = new Color(0.443f, 0.33f, 1f);
        paletteData.entities[0].indexes = new int[]
        {
            33,
            112,
            551,
            12312,
            44431,
            414312
        };
        paletteData.entities[1]         = default(PaletteEntity);
        paletteData.entities[1].color   = new Color(0f, 0f, 1f);
        paletteData.entities[1].indexes = new int[]
        {
            2,
            33,
            14341,
            76412
        };
        paletteData.entities[2]         = default(PaletteEntity);
        paletteData.entities[2].color   = new Color(1f, 0.93f, 0.5412f);
        paletteData.entities[2].indexes = new int[]
        {
            22,
            433,
            4341,
            96412
        };
        FileHelper.SaveStringToFile("example.txt", JsonConvert.SerializeObject(paletteData, Formatting.None, new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore
        }));
    }