The previous code was erroneously assuming that the linesize was equivalent to width*pixel_step, which is not always true.