將一幅圖像取平均值縮小N倍實現方法

        /// <summary>
        /// 將圖像縮小N倍
        /// </summary>
        /// <param name="source">原圖數據</param>
        /// <param name="height">原圖高度</param>
        /// <param name="width">原圖寬度</param>
        /// <param name="scale">縮小倍數</param>
        /// <returns></returns>
        public static ushort[] ImgNarrow(ushort[] source, int height, int width,int scale)
        {
            if (Convert.ToBoolean(height % scale) || Convert.ToBoolean(width % scale))
            {
                throw new Exception("高寬必須爲" + scale + "的倍數");
            }
            ushort[] dest = new ushort[height * width / (scale * scale)];
            int n = 0;
            for (int y = 0; y < height; y = y + scale)
            {
                for (int x = 0; x < width; x = x + scale)
                {
                    int index = y * width + x;
                    int sum = 0;
                    for (int i = 0; i < scale; i++)
                    {
                        for (int j = 0; j < scale; j++)
                        {
                            sum += source[index + i * width + j];
                        }
                    }
                    dest[n] = Convert.ToUInt16(sum / (scale * scale));
                    n++;
                }
            }
            return dest;
        }

原圖是灰度數據,最終的目的是將圖像縮小了N倍,而後取周圍N*N個點的灰度平均值做爲新圖像的值,目前這個實現複雜度有點高,有更優解請評論回覆spa

相關文章
相關標籤/搜索