Следующий код C переворачивает RGB-изображение влево / вправо:
//Flip RGB (or BGR) image Left/Right.
//P is an array of <height> pointers.
//P[0] points first pixel of first row.
//P[1] points first pixel of second row.
//P[height-1] points first pixel of last row.
static void flip_hrizntal_pixels(Pixel **P, int height, int width)
{
//Allocate sketch buffer for storing single flipped row.
Pixel *R = (Pixel*)malloc(width*sizeof(Pixel));
//Stuck here don't know how flip those pixels
for (int i = 0; i < height; i++)
{
Pixel *I0 = P[i]; //Points first pixel in source image
//j is destination index (index of rgb triple in source image I).
for (int j = 0; j < width; j++)
{
//Iterate source row from end of row to beginning of row.
R[j].red = I0[width - j - 1].red;
R[j].green = I0[width - j - 1].green;
R[j].blue = I0[width - j - 1].blue;
}
//Copy flipped row back to image P.
memcpy(I0, R, width*sizeof(Pixel));
}
free(R);
}
Перед выполнением flip_hrizntal_pixels
необходимо подготовить массив указателей.
Вычисление шага изображения в байтах:
stride
- это количество байтов между двумя последовательными строками.
Для формата BMP значение stride
должно быть кратно 4 (дополнено доширина корпуса не кратна 4).
int stride = width*3;
//For supporting width that is not a multiple of 4, stride in bytes is padded up to nearest multiple of 4 bytes.
stride = (stride + 3) & (~3); //http://mapw.elte.hu/elek/bmpinmemory.html
Подготовка массива указателей на строки:
Предположим, I
- указатель на входное изображение.
//Prepare and array of pointers to rows:
//////////////////////////////////////////////////////////////////////////
//P[0] -> Points beginning of first row.
//P[1] -> Points beginning of second row.
//...
//P[height-1] -> Points beginning of last row.
//Allocate array of <height> pointers.
Pixel **P = (Pixel**)malloc(height*sizeof(Pixel*));
for (int i = 0; i < height; i++)
{
P[i] = (Pixel*)((char*)I + stride*i); //Advance by <stride> bytes from row to row.
}
//////////////////////////////////////////////////////////////////////////
Выполнение flip_hrizntal_pixels
:
flip_hrizntal_pixels(P,
height,
width);
Очистка:
free(P);
Тестирование (peppers.png
изображение из MATLAB):
Входное изображение:
Выходное изображение:
