Flipping an image to get mirror effect
Asked Answered
H

4

16

I am working on a video processing project which needs some flipping of frame. I tried using cvFlip but doesnt seem to flip along y axis (x axis working...) and results in segmentation fault. Is there any other option??

cv::Mat dst=src;      //src= source image from cam
cv::flip(dst, dst, 1);     //segmentation fault shown

imshow("flipped",dst);
Handwork answered 17/2, 2013 at 10:44 Comment(4)
Please post the relevant code so people can help you fix it.Preterition
How is this related to Qt?Eurythmics
@Stephen Chu not at allKeelykeen
I mentioned it becoz I am working with qt and opencv in Qt creator IDeHandwork
K
16
cv::Mat src=imload("bla.png");
cv::Mat dst;               // dst must be a different Mat
cv::flip(src, dst, 1);     // because you can't flip in-place (leads to segfault)
Keelykeen answered 17/2, 2013 at 11:47 Comment(1)
In-place flip should not be a problem. I checked the source code of 4.2 and 4.8. According to the source code. dst is always created as a new matrix. : github.com/opencv/opencv/blob/…Bagger
S
9

Use cv::flip and pass 1 as flipcode.

Looking at your edit with the sample code, you cannot flip in place. You need a separate destination cv::Mat:

cv::Mat dst;
cv::flip(src, dst, 1);
imshow("flipped",dst);
Strade answered 17/2, 2013 at 10:47 Comment(2)
I tried with separate destination as well stil showing segmentation fault!Handwork
@Handwork Actually the documentation seems to imply that the destination array has to be preallocated, for example by doing dst.create(src.size(),src.type()); . I could not verify if this is strictly necessary.Inheritable
P
6

The key is to create the dst exactly like the src:

cv::Mat dst = cv::Mat(src.rows, src.cols, CV_8UC3);
cv::flip(src, dst, 1);

imshow("flipped", dst);
Parol answered 28/4, 2016 at 21:38 Comment(1)
It is not necessary to set dst = cv::Mat(src.rows, src.cols, CV_8UC3); the flip function handles that automatically.Gynaecomastia
G
1

At least in openCV 4.8, you can flip in place (with both cv::Mat and cv::UMat).

A possible sample code:

// buffer is a pointer to data, for example:
// uint8_t* buffer = new uint8_t[w*h*4]
// CV_8UC4 means unsigned byte, 4 channel image (for example RGBA)
// UMat allows to use GPU acceleration, it may be useful or not depending
// on the scenario, or you can simply just use cv::Mat.
cv::UMat m = cv::Mat(h , w, CV_8UC4, buffer).getUMat(cv::ACCESS_READ);
// flip accepts a flag that can be 0, <0 or >0
// here I put zero cause if the image is taken in landscape mode, although // looks like it needs vertical mirroring, it is actually horizontal. So you // may want to try the various options if 1 doesn't work as expected
flip(m, m, 0);
Gilpin answered 30/1 at 2:51 Comment(1)
Yes, I also think you can flip, and perform other OpenCV mat operations, in place.Brubeck

© 2022 - 2024 — McMap. All rights reserved.