美文网首页
重现image resize - 最邻近算法

重现image resize - 最邻近算法

作者: Zz鱼丸 | 来源:发表于2017-11-20 16:19 被阅读0次

实习第一个任务就是摆脱opencv,写出图像的resize算法。难。。。
现在总结一下:
由于目前还需要opencv进行图像的读取和显式,所以还是会用到opencv的库。之后应该慢慢就有公司自己的库了。
图像的缩放很好理解,就是图像的放大和缩小。传统的绘画工具中,有一种叫做“放大尺”的绘画工具,画家常用它来放大图画。当然,在计算机上,我们不再需要用放大尺去放大或缩小图像了,把这个工作交给程序来完成就可以了。下面就来讲讲计算机怎么来放大缩小图象;在本文中,我们所说的图像都是指点阵图,也就是用一个像素矩阵来描述图像的方法,对于另一种图像:用函数来描述图像的矢量图,不在本文讨论之列。
越是简单的模型越适合用来举例子,我们就举个简单的图像:3X3 的256级灰度图,也就是高为3个象素,宽也是3个象素的图像,每个象素的取值可以是 0-255,代表该像素的亮度,255代表最亮,也就是白色,0代表最暗,即黑色。假如图像的象素矩阵如下图所示(这个原始图把它叫做源图,Source):
234 38 22
67 44 12
89 65 63
这个矩阵中,元素坐标(x,y)是这样确定的,x从左到右,从0开始,y从上到下,也是从零开始,这是图象处理中最常用的坐标系,就是这样一个坐标:
---------------------->X
|
|
|
|
|
∨Y
如果想把这副图放大为 4X4大小的图像,那么该怎么做呢?那么第一步肯定想到的是先把4X4的矩阵先画出来再说,好了矩阵画出来了,如下所示,当然,矩阵的每个像素都是未知数,等待着我们去填充(这个将要被填充的图的叫做目标图,Destination):
? ? ? ?
? ? ? ?
? ? ? ?
? ? ? ?

然后要往这个空的矩阵里面填值了,要填的值从哪里来来呢?是从源图中来,好,先填写目标图最左上角的象素,坐标为(0,0),那么该坐标对应源图中的坐标可以由如下公式得出:
srcX=dstX* (srcWidth/dstWidth) , srcY = dstY * (srcHeight/dstHeight)
好了,套用公式,就可以找到对应的原图的坐标了(0(3/4),0(3/4))=>(00.75,00.75)=>(0,0)
,找到了源图的对应坐标,就可以把源图中坐标为(0,0)处的234象素值填进去目标图的(0,0)这个位置了。
接下来,如法炮制,寻找目标图中坐标为(1,0)的象素对应源图中的坐标,套用公式:
(10.75,00.75)=>(0.75,0)
结果发现,得到的坐标里面竟然有小数,这可怎么办?计算机里的图像可是数字图像,象素就是最小单位了,象素的坐标都是整数,从来没有小数坐标。这时候采用的一种策略就是采用四舍五入的方法(也可以采用直接舍掉小数位的方法),把非整数坐标转换成整数,好,那么按照四舍五入的方法就得到坐标(1,0),完整的运算过程就是这样的:
(10.75,00.75)=>(0.75,0)=>(1,0)
那么就可以再填一个象素到目标矩阵中了,同样是把源图中坐标为(1,0)处的像素值38填入目标图中的坐标。

依次填完每个象素,一幅放大后的图像就诞生了,像素矩阵如下所示:
234 38 22 22
67 44 12 12
89 65 63 63
89 65 63 63
这种放大图像的方法叫做最临近插值算法,这是一种最基本、最简单的图像缩放算法,效果也是最不好的,放大后的图像有很严重的马赛克,缩小后的图像有很严重的失真;效果不好的根源就是其简单的最临近插值方法引入了严重的图像失真,比如,当由目标图的坐标反推得到的源图的的坐标是一个浮点数的时候,采用了四舍五入的方法,直接采用了和这个浮点数最接近的象素的值,这种方法是很不科学的,当推得坐标值为 0.75的时候,不应该就简单的取为1,既然是0.75,比1要小0.25 ,比0要大0.75 ,那么目标象素值其实应该根据这个源图中虚拟的点四周的四个真实的点来按照一定的规律计算出来的,这样才能达到更好的缩放效果。双线型内插值算法就是一种比较好的图像缩放算法,它充分的利用了源图中虚拟点四周的四个真实存在的像素值来共同决定目标图中的一个像素值,因此缩放效果比简单的最邻近插值要好很多。
基于此原理的代码如下:

/*********************Resize_INTER_NN******************************************/
//功能:利用最临近插值修改图像尺寸
//参数:原图像,目标图像,目标长,目标宽
void mcv::Resize_INTER_NN(mcv::Image &src, mcv::Image &dst, unsigned int width, unsigned int heigth)
{
    matDst1 = Mat(Size(width, heigth), matSrc.type(), Scalar::all(0));//为了显示使用opencv,Size(width,heigth)

    dst.height = matDst1.rows;
    dst.width = matDst1.cols;
    dst.channel = matDst1.channels();
    dst.data = matDst1.data;
    //缩放倍数
    double scale_x = (double)src.width / dst.width;
    double scale_y = (double)src.height / dst.height;

    //最临近插值
    //unsigned char * ptr = dst.data;//储存基地址  改进后不需要了
    for (int i = 0; i < dst.width; i++)
    {
        int sx = floor(i * scale_x);
        sx = std::min(sx, src.width - 1);
        for (int j = 0; j < dst.height; j++)
        {
            int sy = floor(j * scale_y);
            sy = std::min(sy, src.height - 1);

            for (int k = 0; k < dst.channel; k++)
            {
                if ((i == 1) && (j == 0) && (k == 0))
                    waitKey(1000);
                //dst.data = ptr + i*dst.channel + j*dst.width*dst.channel + k;
                *(dst.data + i*dst.channel + j*dst.width*dst.channel + k) = *(src.data + sx*src.channel + sy*src.channel*src.width + k);//w*h*ch变换到1维中
            }
        }
    }
}

结果如下


image.png

肉眼看不出,对比十六进制:


image.png
看出基于原理写的代码和opencv出来的结果相差很多,这样是交不了差的。。。

插值方法:

  • CV_INTER_NN - 最近邻插值,
  • CV_INTER_LINEAR - 双线性插值 (缺省使用)
  • CV_INTER_AREA - 使用象素关系重采样。当图像缩小时候,该方法可以避免波纹出现。当图像放大时,类似于 CV_INTER_NN 方法..
  • CV_INTER_CUBIC - 立方插值.
    下面我放出关键代码,如果需要完整的请私信我。
//******************定义的临时图像类型*************//
    class Image{
    public:
        unsigned char* data;
        int height;
        int width;
        int depth;
        int step;
        int dims;
        int elemSize;
        int channel;
    };//以后慢慢丰富
//******************动态管理内存****************//
   template<typename _Tp, msize_t fixed_size = 4096 / sizeof(_Tp)+8> class mAutoBuffer
   {
   public:
       typedef _Tp value_type;
       enum { buffer_padding = (int)((16 + sizeof(_Tp)-1) / sizeof(_Tp)) };

       //! the default contructor
       mAutoBuffer();
       //! constructor taking the real buffer size
       mAutoBuffer(msize_t _size);
       //! destructor. calls deallocate()
       ~mAutoBuffer();

       //! allocates the new buffer of size _size. if the _size is small enough, stack-allocated buffer is used
       void mallocate(msize_t _size);
       //! deallocates the buffer if it was dynamically allocated
       void mdeallocate();
       //! returns pointer to the real buffer, stack-allocated or head-allocated
       operator _Tp* ();
       //! returns read-only pointer to the real buffer, stack-allocated or head-allocated
       operator const _Tp* () const;

   protected:
       //! pointer to the real buffer, can point to buf if the buffer is small enough
       _Tp* ptr;
       //! size of the real buffer
       msize_t size;
       //! pre-allocated buffer
       _Tp buf[fixed_size + buffer_padding];
   };
   template<typename _Tp> static inline _Tp* mallocate(msize_t n)
   {
       return new _Tp[n];
   }

   template<typename _Tp> static inline void mdeallocate(_Tp* ptr, msize_t)
   {
       delete[] ptr;
   }
   template<typename _Tp, msize_t fixed_size> inline mAutoBuffer<_Tp, fixed_size>::mAutoBuffer()
   {
       ptr = buf;
       size = fixed_size;
   }

   template<typename _Tp, msize_t fixed_size> inline mAutoBuffer<_Tp, fixed_size>::mAutoBuffer(msize_t _size)
   {
       ptr = buf;
       size = fixed_size;
       mallocate(_size);
   }

   template<typename _Tp, msize_t fixed_size> inline mAutoBuffer<_Tp, fixed_size>::~mAutoBuffer()
   {
       mdeallocate();
   }

   template<typename _Tp, msize_t fixed_size> inline void mAutoBuffer<_Tp, fixed_size>::mallocate(msize_t _size)
   {
       if (_size <= size)
           return;
       mdeallocate();
       if (_size > fixed_size)
       {
           ptr = mcv::mallocate<_Tp>(_size);
           size = _size;
       }
   }

   template<typename _Tp, msize_t fixed_size> inline void mAutoBuffer<_Tp, fixed_size>::mdeallocate()
   {
       if (ptr != buf)
       {
           mcv::mdeallocate<_Tp>(ptr, size);
           ptr = buf;
           size = fixed_size;
       }
   }

   template<typename _Tp, msize_t fixed_size> inline mAutoBuffer<_Tp, fixed_size>::operator _Tp* ()
   {
       return ptr;
   }

   template<typename _Tp, msize_t fixed_size> inline mAutoBuffer<_Tp, fixed_size>::operator const _Tp* () const
   {
       return ptr;
   }
void mcv::Resize_NN(mcv::Image &src, mcv::Image &dst, int height, int width)
{
    matDst1 = Mat(Size(width, height), matSrc.type(), Scalar::all(0));
    dst.height = matDst1.rows;
    dst.width = matDst1.cols;
    dst.channel = matDst1.channels();
    dst.step = matDst1.step;
    dst.dims = matDst1.dims;
    dst.depth = matDst1.depth();
    dst.elemSize = (int)matDst1.elemSize();
    dst.data = matDst1.data;

    //缩放倍数
    double inv_scale_x = (double)dst.width / src.width;
    double inv_scale_y = (double)dst.height / src.height;

    double scale_x = 1. / inv_scale_x, scale_y = 1. / inv_scale_y;
    int depth = src.depth, cn = src.channel;


    int fx, fy;
    int k, sx, sy, dx, dy;
    mcv::mAutoBuffer<int> _x_ofs(dst.width);
    int* x_ofs = _x_ofs;
    fx = inv_scale_x; fy = inv_scale_y;
    int pix_size = src.elemSize;
    int pix_size4 = (int)(pix_size / sizeof(int));
    double ifx = 1. / fx, ify = 1. / fy;

    int x1;
    for (x1 = 0; x1 < dst.width; x1++)
    {
        int sx = floor(x1*ifx);
        x_ofs[x1] = std::min(sx, src.width - 1)*pix_size;
    }
    mcv::mRange range(0, dst.height);
    int y, x;
    for (int y = range.start; y < range.end; y++)
    {
        uchar* D = dst.data + dst.step*y;
        int sy = std::min(cvFloor(y*ify), dst.height - 1);
        const uchar* S = src.data + src.step*sy;

        switch (pix_size)
        {
        case 1:
            for (x = 0; x <= dst.width - 2; x += 2)
            {
                uchar t0 = S[x_ofs[x]];
                uchar t1 = S[x_ofs[x + 1]];
                D[x] = t0;
                D[x + 1] = t1;
            }

            for (; x < dst.width; x++)
                D[x] = S[x_ofs[x]];
            break;
        case 2:
            for (x = 0; x < dst.width; x++)
                *(ushort*)(D + x * 2) = *(ushort*)(S + x_ofs[x]);
            break;
        case 3:
            for (x = 0; x < dst.width; x++, D += 3)
            {
                const uchar* _tS = S + x_ofs[x];
                D[0] = _tS[0]; D[1] = _tS[1]; D[2] = _tS[2];
            }
            break;
        case 4:
            for (x = 0; x < dst.width; x++)
                *(int*)(D + x * 4) = *(int*)(S + x_ofs[x]);
            break;
        case 6:
            for (x = 0; x < dst.width; x++, D += 6)
            {
                const ushort* _tS = (const ushort*)(S + x_ofs[x]);
                ushort* _tD = (ushort*)D;
                _tD[0] = _tS[0]; _tD[1] = _tS[1]; _tD[2] = _tS[2];
            }
            break;
        case 8:
            for (x = 0; x < dst.width; x++, D += 8)
            {
                const int* _tS = (const int*)(S + x_ofs[x]);
                int* _tD = (int*)D;
                _tD[0] = _tS[0]; _tD[1] = _tS[1];
            }
            break;
        case 12:
            for (x = 0; x < dst.width; x++, D += 12)
            {
                const int* _tS = (const int*)(S + x_ofs[x]);
                int* _tD = (int*)D;
                _tD[0] = _tS[0]; _tD[1] = _tS[1]; _tD[2] = _tS[2];
            }
            break;
        default:
            for (x = 0; x < dst.width; x++, D += pix_size)
            {
                const int* _tS = (const int*)(S + x_ofs[x]);
                int* _tD = (int*)D;
                for (int k = 0; k < pix_size4; k++)
                    _tD[k] = _tS[k];
            }
        }
    }
}

对比结果


image.png

完美~

这个resizeNN可以实现最邻近插值,而且可以读取灰度图,浮点型图片。

待续...

相关文章

网友评论

      本文标题:重现image resize - 最邻近算法

      本文链接:https://www.haomeiwen.com/subject/rnuwsxtx.html