Move every pixel to right (by 1px) in OpenCV without using remap?
-
26-06-2021 - |
题
I want to move every pixel in an image to right by 1px, and below is the map I use to do the remap transformation.
This approach require much more time than it should to do such a simple transform. Is there a cv function I can use? Or do I just split the image into 2 images, one is src.cols-1 pixels wide, the other is 1 px wide, and then copy them to the new image?
void update_map()
{
for( int j = 0; j < src.cols; j++ ){
for( int i = 0; i < src.rows; i++ ){
if (j == src.cols-1)
mat_x_Rotate.at<float>(i,j) = 0;
else
mat_x_Rotate.at<float>(i,j) = j + 1;
mat_y_Rotate.at<float>(i,j) = i;
}
}
}
解决方案
Things you can do to improve your performance:
- remap is overkill for this purpose. It is more efficient to copy the pixels directly than to define an entire remap transformation and then use it.
- switch your loop order: iterate over rows, then columns. (OpenCV's
Mat
is stored in row-major order, so iterating over columns first is very cache-unfriendly) - use
Mat::ptr()
to access pixels in the same row directly, as a C-style array. (this is a big performance win over usingat<>()
, which probably does stuff like check indices for each access) - take your
if
statement out of the inner loop, and handle column0
separately.
As an alternative: yes, splitting the image into parts and copying to the new image might be about as efficient as copying directly, as described above.
其他提示
Mat Shift_Image_to_Right( Mat src_in, int num_pixels)
{
Size sz_src_in = src_in.size();
Mat img_out(sz_src_in.height, sz_src_in.width, CV_8UC3);
Rect roi;
roi.x = 0;
roi.y = 0;
roi.width = sz_src_in.width-num_pixels;
roi.height = sz_src_in.height;
Mat crop;
crop = src_in(roi);
// Move the left boundary to the right
img_out = Scalar::all(0);
img_out.adjustROI(0, 0, -num_pixels, 0);
crop.copyTo(img_out);
img_out.adjustROI(0, 0, num_pixels, 0);
return img_out;
}
不隶属于 StackOverflow