Esempio n. 1
0
    public static Mat ConvertFlowMap(Mat src, float strength, bool isFlipV)
    {
        var width       = src.Width;
        var height      = src.Height;
        var srcIndexer  = src.GetGenericIndexer <Vec2f>();
        var dst         = new Mat(height, width, MatType.CV_8UC4);
        var dstIndexer  = dst.GetGenericIndexer <Vec4b>();
        var invStrength = 1.0f / strength;
        var aspect      = 1;   //(float)height / width;// / (float)height;
        var flipV       = (isFlipV == true) ? 1 : -1;

        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                var srcColor = srcIndexer[y, x];
                var vec      = new Vector2(srcColor[0], srcColor[1] * flipV * aspect);
                vec *= invStrength;
                var r = (byte)(Mathf.Clamp01(vec.x * 0.5f + 0.5f) * 255.0f);
                var g = (byte)(Mathf.Clamp01(vec.y * 0.5f + 0.5f) * 255.0f);
                dstIndexer[y, x] = new Vec4b(255, 0, g, r);
            }
        }
        return(dst);
    }
Esempio n. 2
0
        public void ConversionVec4b()
        {
            var v = new Vec4b(1, 2, 3, 4);

            Assert.Equal(new Vec4s(1, 2, 3, 4), v.ToVec4s());
            Assert.Equal(new Vec4w(1, 2, 3, 4), v.ToVec4w());
            Assert.Equal(new Vec4i(1, 2, 3, 4), v.ToVec4i());
            Assert.Equal(new Vec4f(1, 2, 3, 4), v.ToVec4f());
            Assert.Equal(new Vec4d(1, 2, 3, 4), v.ToVec4d());
        }
Esempio n. 3
0
        public static Vec4b applyFading(Scalar val, float current_alpha, Scalar current_clr)
        {
            Vec4b out_ = new Vec4b();

            out_[0] = _applyFading(val[0], current_alpha, current_clr[0]);
            out_[1] = _applyFading(val[1], current_alpha, current_clr[1]);
            out_[2] = _applyFading(val[2], current_alpha, current_clr[2]);
            out_[3] = 255;
            return(out_);
        }
Esempio n. 4
0
//æææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææ
//æææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææ
//æææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææææ

    public Vec4b readColor(BinaryReader br)
    {
        Vec4b c = new Vec4b();

        c.X = br.ReadByte();
        c.Y = br.ReadByte();
        c.Z = br.ReadByte();
        c.W = br.ReadByte();
        return(c);
    }
Esempio n. 5
0
        //private static Mat whiteHist = null;
        //private static int[] hdims = { 256 }; // Histogram size for each dimension
        //private static Rangef[] ranges = { new Rangef(0, 256), }; // min/max
        public static bool IsImageWhite(Mat pieceMat, float compareDiff = 0.45f)
        {
            int count_transparent = 0;

            for (int row = 0; row < pieceMat.Rows; row++)
            {
                for (int col = 0; col < pieceMat.Cols; col++)
                {
                    Vec4b val = pieceMat.At <Vec4b>(row, col);
                    if (val[3] > 0)
                    {
                        count_transparent++;
                    }
                }
            }
            int totalIdx = pieceMat.Cols * pieceMat.Rows;

            return(count_transparent / totalIdx < compareDiff);

            // if (whiteHist == null)
            // {
            //     Mat whitePieceToCompare = pieceMat.EmptyClone();
            //     whitePieceToCompare.SetTo(Scalar.White);
            //     whiteHist = new Mat();
            //
            //     Cv2.CalcHist(
            //         new Mat[] { whitePieceToCompare },
            //         new int[] { 0 },
            //         null,
            //         whiteHist,
            //         1,
            //         hdims,
            //         ranges);
            // }
            //
            //
            // Mat hist1 = new Mat();
            //
            // Cv2.CalcHist(
            //     new Mat[] { pieceMat },
            //     new int[] { 0 },
            //     null,
            //     hist1,
            //     1,
            //     hdims,
            //     ranges);
            //
            //
            // double histDiff = Cv2.CompareHist(hist1, whiteHist, HistCompMethods.Bhattacharyya);
            // //Debug.Log("hist val:" + histDiff);
            // if (Math.Round(histDiff, 2) < compareDiff) // < 0,5 white
            //     return true;
            // else
            //     return false;
        }
Esempio n. 6
0
        Vec4b ParseRawColor(uint rawColor)
        {
            Vec4b color = new Vec4b();

            for (int j = 0; j < 4; ++j)
            {
                color[j] = (byte)((rawColor >> (j * 8)) & 0xff);
            }

            return(color);
        }
Esempio n. 7
0
        /// <summary>
        /// function AlphaBlending()
        /// </summary>
        /// <param name="underlying_image"></param>
        /// <param name="overlay_image"></param>
        /// <returns></returns>
        private static Mat AlphaBlending(Mat underlying_image, Mat overlay_image)
        {
            Mat result_image = new Mat(new Size(underlying_image.Width, underlying_image.Height), MatType.CV_8UC4, Scalar.All(255));

            int imageWidth = underlying_image.Width;
            int imageHeight = underlying_image.Height;
            int i, j;

            // if the image size of underlying image is different from that of overlay image, just return the underlying image
            if ((underlying_image.Width != overlay_image.Width) ||
                (underlying_image.Height != overlay_image.Height))
            {
                Console.WriteLine("ERROR : The sizes of two images must be the same.");
                result_image = underlying_image.Clone();

                return(result_image);
            }


            // pixel-wise alpha blending
            for (i = 0; i < imageWidth; i++)
            {
                for (j = 0; j < imageHeight; j++)
                {
                    var underlying_color = underlying_image.Get <Vec4b>(j, i);
                    var overlay_color    = overlay_image.Get <Vec4b>(j, i);
                    var result_color     = new Vec4b();

                    double alpha = (double)(overlay_color.Item3 / 255.0);

                    // calculate alpha blending
                    result_color.Item0 = (byte)(overlay_color.Item0 * alpha + underlying_color.Item0 * (1 - alpha));
                    result_color.Item1 = (byte)(overlay_color.Item1 * alpha + underlying_color.Item1 * (1 - alpha));
                    result_color.Item2 = (byte)(overlay_color.Item2 * alpha + underlying_color.Item2 * (1 - alpha));
                    result_color.Item3 = (byte)255;

                    result_image.Set(j, i, result_color);
                }
            }

            return(result_image);
        }
Esempio n. 8
0
        // Loads the given model into a voxel set and returns it.
        VoxelSet <Vec4b> LoadModelChunk(Chunk sizeChunk, Chunk idxChunk)
        {
            if (sizeChunk.chunkId != kChunkSize)
            {
                throw new Exception("Bad size chunk");
            }

            if (idxChunk.chunkId != kChunkXyzi)
            {
                throw new Exception("Bad index chunk");
            }

            BinaryReader sizeReader = sizeChunk.OpenReader();
            BinaryReader idxReader  = idxChunk.OpenReader();

            // TODO: This seems to load models rotated 180 degrees
            Vec3i size = new Vec3i();

            size.x = sizeReader.ReadInt32();
            size.z = sizeReader.ReadInt32();
            size.y = sizeReader.ReadInt32();
            VoxelSet <Vec4b> model = new VoxelSet <Vec4b>(size);

            // Read individual voxels
            int numVoxels = idxReader.ReadInt32();

            for (int j = 0; j < numVoxels; ++j)
            {
                //Vec3i idx = new Vec3i(br.ReadByte(), br.ReadByte(), br.ReadByte());
                Vec3i idx = new Vec3i(0);
                idx.x = idxReader.ReadByte();
                idx.z = idxReader.ReadByte();
                idx.y = idxReader.ReadByte();

                // For now just store the index into the palette
                model[idx] = new Vec4b(idxReader.ReadByte());
            }

            return(model);
        }
Esempio n. 9
0
    public static Mat ConvertFromTexture2d(Texture2D texture2d, int indexX, int indexY, int tileX, int tileY)
    {
        var texWidth  = texture2d.width;
        var texHeight = texture2d.height;
        var width     = texWidth / tileX;
        var height    = texHeight / tileY;
        var pixels    = texture2d.GetPixels32();
        var mat       = new Mat(height, width, MatType.CV_8UC4);
        //	Debug.Log( string.Format( "ix:{0} iy:{1}", indexX, indexY ) );
        var indexer = mat.GetGenericIndexer <Vec4b>();

        for (int y = 0; y < height; y++)
        {
            int py = ((((tileY - 1) - indexY) * height) + y) * texWidth;
            for (int x = 0; x < width; x++)
            {
                int px       = (indexX * width) + x;
                var srcColor = pixels[py + px];
                indexer[y, x] = new Vec4b(255, srcColor.b, srcColor.g, srcColor.r);
            }
        }
        return(mat);
    }
 public static extern ExceptionStatus core_Mat_push_back_Vec4b(IntPtr self, Vec4b v);
        public void ImgCutProc(bool saveFlg)
        {
            var array   = File.ReadAllBytes(this._loadImgStr);
            var mat     = Cv2.ImDecode(array, ImreadModes.Color);
            Mat srcImg  = Cv2.ImDecode(array, ImreadModes.Color);
            Mat maskImg = new Mat(srcImg.Rows, srcImg.Cols, MatType.CV_8UC3, new Scalar(0, 0, 0));

            for (int i = 0; i < _linePointList.Count; i++)
            {
                int list_i = i;
                if (i > _linePointList.Count - 1)
                {
                    list_i = 0;
                }
                Cv2.Line(maskImg, new OpenCvSharp.Point(_drawLine[list_i].X1, _drawLine[list_i].Y1),
                         new OpenCvSharp.Point(_drawLine[list_i].X2, _drawLine[list_i].Y2),
                         new Scalar(255, 255, 255));
            }
            Cv2.FloodFill(maskImg, new OpenCvSharp.Point(0, 0), new Scalar(255, 255, 255, 255));
            Cv2.BitwiseNot(maskImg, maskImg);
            Mat dstImg = new Mat();

            srcImg.CopyTo(dstImg, maskImg);
            Cv2.CvtColor(dstImg, dstImg, ColorConversionCodes.BGR2BGRA);
#if DEBUG
            var minIdxX = _drawLine
                          .Select((val, idx) => new { inVal = val, inIdx = idx })
                          .Aggregate((min, compareVal) => (min.inVal.X1 < compareVal.inVal.X1) ? min : compareVal)
                          .inIdx;
            var maxIdxX = _drawLine
                          .Select((val, idx) => new { inVal = val, inIdx = idx }).
                          Aggregate((max, compareVal) => (max.inVal.X1 > compareVal.inVal.X1) ? max : compareVal)
                          .inIdx;
            var minIdxY = _drawLine
                          .Select((val, idx) => new { V = val, I = idx })
                          .Aggregate((min, working) => (min.V.Y1 < working.V.Y1) ? min : working)
                          .I;
            var maxIdxY = _drawLine
                          .Select((val, idx) => new { V = val, I = idx }).
                          Aggregate((max, working) => (max.V.Y1 > working.V.Y1) ? max : working).
                          I;
            Console.WriteLine("min index in X" + minIdxX);
            Console.WriteLine("max index in X" + maxIdxX);
            Console.WriteLine("min index in Y" + minIdxY);
            Console.WriteLine("max index in Y" + maxIdxY);
            Console.WriteLine(_linePointList.Select(x => x.X).Min());
            Console.WriteLine(_linePointList.Select(x => x.Y).Max());
            Console.WriteLine(_linePointList.Select(y => y.Y).Min());
            Console.WriteLine(_linePointList.Select(y => y.Y).Max());
#endif
            for (int y = 0; y < dstImg.Rows; ++y)
            {
                for (int x = 0; x < dstImg.Cols; ++x)
                {
                    Vec4b px = dstImg.At <Vec4b>(y, x);
                    if (px[0] + px[1] + px[2] == 0)
                    {
                        px[3] = 0;
                        dstImg.Set <Vec4b>(y, x, px);
                    }
                }
            }
            if (saveFlg)
            {
                var dialog = new SaveFileDialog();
                dialog.Title            = "ファイルの保存先を選択してね!";
                dialog.InitialDirectory = @"C:\Users";
                dialog.FileName         = "cutimg.png";
                dialog.Filter           = "すべてのファイル|*.*|png ファイル|*.png|bmp ファイル|*.bmp|jpeg ファイル|*.jpeg";
                dialog.RestoreDirectory = true;
                dialog.FilterIndex      = 2;
                if (true == dialog.ShowDialog())
                {
                    Cv2.ImWrite(dialog.FileName, dstImg);
                }
            }
            else
            {
                Cv2.ImShow("dstImg", dstImg);
            }
        }
Esempio n. 12
0
        public void GetMesh(VoxelSet <Vec4b> voxels,
                            out int[] indices, out Vec3f[] points, out Vec3f[] normals, out Vec2f[] uvs,
                            out VoxelSet <Vec4b> textureAtlas)
        {
            List <int>   indicesList = new List <int>();
            List <Vec3f> pointsList  = new List <Vec3f>();
            List <Vec3f> normalsList = new List <Vec3f>();
            List <Vec2f> uvsList     = new List <Vec2f>();

            Dictionary <int, int> vertIdxRemap = new Dictionary <int, int>();

            List <Bin> bins = new List <Bin>();

            foreach (var poly in AllPolygons())
            {
                // For each connected polygon
                vertIdxRemap.Clear();
                Vec3f normal = Normal(poly.First());

                Vec3f maxP = new Vec3f(-1);
                Vec3f minP = new Vec3f(1024 * 1024);

                AtlasEntry atlasEntry = new AtlasEntry();
                atlasEntry.startVertIdx = pointsList.Count;
                atlasEntry.normal       = new Vec3i(
                    (int)Math.Round(normal.x),
                    (int)Math.Round(normal.y),
                    (int)Math.Round(normal.z)
                    );

                foreach (var baseEdge in poly)
                {
                    // Each triangle that makes up the polygon
                    foreach (var e in new int[] { baseEdge, Next(baseEdge), Prev(baseEdge) })
                    {
                        // Each vertex of each triangle
                        int vertIdx = Edges[e].vertexIdx;
                        if (!vertIdxRemap.ContainsKey(vertIdx))
                        {
                            vertIdxRemap.Add(vertIdx, pointsList.Count);
                            pointsList.Add(Points[vertIdx]);
                            normalsList.Add(normal);

                            maxP = Max3f(maxP, Points[vertIdx]);
                            minP = Min3f(minP, Points[vertIdx]);

                            // TODO: Add UV here
                        }

                        indicesList.Add(vertIdxRemap[vertIdx]);
                    }
                }

                atlasEntry.vertCount = pointsList.Count - atlasEntry.startVertIdx;

                // TODO: Add to texture atlas here
                Vec3f deltaP = maxP - minP;

                // Determine which dimension is flat
                int flatIdx = -1;
                for (int i = 0; i < 3; ++i)
                {
                    if (deltaP[i] == 0)
                    {
                        if (flatIdx >= 0)
                        {
                            throw new Exception("Two or more flat dimensions found");
                        }
                        flatIdx = i;
                    }
                }

                Vec2i size;
                if (flatIdx == 0)
                {
                    size = new Vec2i((int)Math.Round(deltaP.y), (int)Math.Round(deltaP.z));
                }
                else if (flatIdx == 1)
                {
                    size = new Vec2i((int)Math.Round(deltaP.x), (int)Math.Round(deltaP.z));
                }
                else
                {
                    size = new Vec2i((int)Math.Round(deltaP.x), (int)Math.Round(deltaP.y));
                }

                atlasEntry.flatDimension = flatIdx;
                atlasEntry.max           = new Vec3i(maxP + new Vec3f(0.5f));
                atlasEntry.min           = new Vec3i(minP + new Vec3f(0.5f));

                Bin b = new Bin();
                b.Size     = size;
                b.UserData = atlasEntry;
                bins.Add(b);
            }

            indices = indicesList.ToArray();
            points  = pointsList.ToArray();
            normals = normalsList.ToArray();

            //BinPacker bp = new BinPacker(512);
            BinPacker bp = new BinPacker(512);

            bp.BinPadding = new Vec2i(2);
            bp.Pack(bins);
            bp.MakePow2();

            textureAtlas = new VoxelSet <Vec4b>(bp.Width, bp.Height, 1);

            for (int y = 0; y < textureAtlas.Size.y; ++y)
            {
                for (int x = 0; x < textureAtlas.Size.x; ++x)
                {
                    textureAtlas[x, y, 0] = new Vec4b(0, 255, 0, 255);
                }
            }

            uvs = new Vec2f[points.Length];
            foreach (var bin in bp.Bins)
            {
                var atlasEntry = (AtlasEntry)bin.UserData;

                // Copy to atlas
                var toSlice = textureAtlas.Slice(new Vec3i(bin.Position, 0),
                                                 new Vec3i(bin.Position + bin.Size - 1, 0));

                Vec3i voxelOffset = new Vec3i(0);

                if (atlasEntry.normal.Dot(new Vec3i(1)) > 0)
                {
                    voxelOffset = atlasEntry.normal * -1;
                }
                else
                {
                    //voxelOffset = atlasEntry.normal * -1;
                    voxelOffset = new Vec3i(0);
                }

                var fromSlice = voxels.Slice(
                    atlasEntry.min + voxelOffset,
                    atlasEntry.max - atlasEntry.min + atlasEntry.Basis() * new Vec3i(0, 0, 1),
                    atlasEntry.Basis()
                    );

                if (toSlice.Size.x != fromSlice.Size.x ||
                    toSlice.Size.y != fromSlice.Size.y ||
                    toSlice.Size.z != fromSlice.Size.z)
                {
                    throw new Exception();
                }

                /*for (int y = 0; y < toSlice.Size.y; ++y) {
                 *  for (int x = 0; x < toSlice.Size.x; ++x) {
                 *      toSlice[x, y, 0] = fromSlice[x, y, 0];
                 *  }
                 * }*/

                for (int y = 0; y < toSlice.Size.y; ++y)
                {
                    for (int x = 0; x < toSlice.Size.x; ++x)
                    {
                        if (Vec4b.Dot(toSlice[x, y, 0], new Vec4b(1)) != 0)
                        {
                            ////throw new Exception();
                        }
                        toSlice[x, y, 0] = voxels[atlasEntry.To3d(new Vec2i(x, y)) + voxelOffset];
                        //toSlice[x, y, 0] = c;
                    }
                }

                // Compute UVs
                for (int i = atlasEntry.startVertIdx; i < atlasEntry.startVertIdx + atlasEntry.vertCount; ++i)
                {
                    Vec2f uv = new Vec2f(atlasEntry.To2d(new Vec3i(points[i])));

                    //uv *= new Vec2f(bin.Size - 1) / new Vec2f(bin.Size);
                    //uv += 0.5f;

                    uv *= (new Vec2f(bin.Size) - 0.01f) / new Vec2f(bin.Size);
                    uv += 0.005f;

                    /////////
                    //uv *= 0.998f;
                    //uv += 0.01f;

                    uv += new Vec2f(bin.Position);

                    ///////
                    //uv += 0.25f;

                    uv.x /= bp.Width;
                    uv.y /= bp.Height;

                    uvs[i] = uv;
                }
            }

            Console.WriteLine("Total size: {0} x {1}", bp.Width, bp.Height);
        }
 public static extern void core_Mat_push_back_Vec4b(IntPtr self, Vec4b v);
Esempio n. 14
0
 static float ToFloat(Vec4b voxel)
 {
     return(voxel.w / 255.0f);
 }
Esempio n. 15
0
 static bool ToSolid(Vec4b voxel)
 {
     return(voxel.w > 0);
 }
Esempio n. 16
0
 public static extern ExceptionStatus core_FileStorage_shift_Vec4b(IntPtr fs, Vec4b val);
Esempio n. 17
0
 public static extern ExceptionStatus core_FileNode_read_Vec4b(IntPtr node, out Vec4b returnValue);