Бикубический алгоритм изменения размера изображения

Я пытался узнать об алгоритмах изменения размера изображения, таких как ближайший сосед, бикубические и билинейные алгоритмы интерполяции. Я немного изучил математику, и теперь я смотрю на существующие реализации, чтобы понять и оценить, как они работают.

Я начал с эта реализация Bi-Cubic Resize, которую я нашел в коде Google, который использует OpenCV и предоставляет тестовый и примерный код. Я использовал его в качестве отправной точки для своей собственной реализации, которая не использует OpenCV, а просто работает с необработанным растровым изображением, содержащимся в std::vector<unsigned char>:

std::vector<unsigned char> bicubicresize(const std::vector<unsigned char>& in, std::size_t src_width,
    std::size_t src_height, std::size_t dest_width, std::size_t dest_height)
{
    std::vector<unsigned char> out(dest_width * dest_height * 3);

    const float tx = float(src_width) / dest_width;
    const float ty = float(src_height) / dest_height;
    const int components = 3;
    const int bytes_per_row = src_width * components;

    const int components2 = components;
    const int bytes_per_row2 = dest_width * components;

    int a, b, c, d, index;
    unsigned char Ca, Cb, Cc;
    unsigned char C[5];
    unsigned char d0, d2, d3, a0, a1, a2, a3;

    for (int i = 0; i < dest_height; ++i)
    {
        for (int j = 0; j < dest_width; ++j)
        {
            const int x = int(tx * j);
            const int y = int(ty * i);
            const float dx = tx * j - x;
            const float dy = ty * i - y;

            index = y * bytes_per_row + x * components;
            a = y * bytes_per_row + (x + 1) * components;
            b = (y + 1) * bytes_per_row + x * components;
            c = (y + 1) * bytes_per_row + (x + 1) * components;

            for (int k = 0; k < 3; ++k)
            {
                for (int jj = 0; jj <= 3; ++jj)
                {
                    d0 = in[(y - 1 + jj) * bytes_per_row + (x - 1) * components + k] - in[(y - 1 + jj) * bytes_per_row + (x) * components + k];
                    d2 = in[(y - 1 + jj) * bytes_per_row + (x + 1) * components + k] - in[(y - 1 + jj) * bytes_per_row + (x) * components + k];
                    d3 = in[(y - 1 + jj) * bytes_per_row + (x + 2) * components + k] - in[(y - 1 + jj) * bytes_per_row + (x) * components + k];
                    a0 = in[(y - 1 + jj) * bytes_per_row + (x) * components + k];
                    a1 = -1.0 / 3 * d0 + d2 - 1.0 / 6 * d3;
                    a2 = 1.0 / 2 * d0 + 1.0 / 2 * d2;
                    a3 = -1.0 / 6 * d0 - 1.0 / 2 * d2 + 1.0 / 6 * d3;
                    C[jj] = a0 + a1 * dx + a2 * dx * dx + a3 * dx * dx * dx;

                    d0 = C[0] - C[1];
                    d2 = C[2] - C[1];
                    d3 = C[3] - C[1];
                    a0 = C[1];
                    a1 = -1.0 / 3 * d0 + d2 -1.0 / 6 * d3;
                    a2 = 1.0 / 2 * d0 + 1.0 / 2 * d2;
                    a3 = -1.0 / 6 * d0 - 1.0 / 2 * d2 + 1.0 / 6 * d3;
                    Cc = a0 + a1 * dy + a2 * dy * dy + a3* dy * dy * dy;
                    out[i * bytes_per_row2 + j * components2 + k] = Cc;
                }
            }
        }
    }

    return out;   
}



Насколько я вижу, эта реализация фатально ошибочна из-за строки:

d0 = in[(y - 1 + jj) * bytes_per_row + (x - 1) * components + k] - in[(y - 1 + jj) * bytes_per_row + (x) * components + k];



Мне кажется, что эта строка будет всегда обращаться к индексу массива за пределами границ, когда y равно 0. И y изначально всегда будет 0, потому что y инициализируется y = ty * i, а i — это переменная итератора, начинающаяся с 0. Так как y всегда будет начинаться с 0, выражение (y - 1 + jj) * bytes_per_row + (x - 1) * components + k (которое используется для вычисления ИНДЕКСА МАССИВА) всегда будет отрицательным. И... очевидно, отрицательный индекс массива недействителен.

Вопрос: мне кажется, что этот код не может работать. Я как-то не прав?


person Channel72    schedule 28.02.2013    source источник
comment
Мне, FWIW, ваше наблюдение кажется правильным.   -  person 500 - Internal Server Error    schedule 28.02.2013


Ответы (2)


Один из способов сделать это — определить функцию GetPixel():

GetPixel(int x, int y, int channel)
{
   if (x >= 0 && x <= width-1)
      if (y >=0 && y <= height-1)
         return QueriedPixelFromImage(x,y,channel);
   return 0; // out of bounds
}

Вы замените

d0 = in[(y - 1 + jj) * bytes_per_row + (x - 1) * components + k]

by

d0 = GetPixel(x-1,y-1+jj,k)
person Boyko Perfanov    schedule 28.02.2013

Я запустил тестовый код, чтобы убедиться, что ничего не упустил, но, насколько я вижу, вы действительно правы:

#include <iostream>

int main()
{

  int components = 3;

  const float tx = 200/50;
  const float ty = 200/50 ;
  int bytes_per_row = 1000 ;

  for (int i = 0; i < 5; ++i)
  {
    for (int j = 0; j < 5; ++j)
    {
         const int x = int(tx * j);
         const int y = int(ty * i);

        for (int k = 0; k < 3; ++k)
        {
            for (int jj = 0; jj <= 3; ++jj)
            {
               std::cout << "calc: " << (y - 1 + jj) * bytes_per_row + (x - 1) * components + k << std::endl ;
            }
        }
     }
   }
}

Я взглянул на код на сайте, который вы предоставили, и он не похож на очень большой проект. Поэтому, возможно, вам следует связаться с сопровождающими проекта и посмотреть, могут ли они помочь. На главной странице http://code.google.com/a/eclipselabs.org/p/bicubic-interpolation-image-processing/

person Shafik Yaghmour    schedule 28.02.2013