Search code examples
opencvcgaffinetransformflip

Why I cannot flip an image with opencv affine transform?


I have read about affine transform in wikipedia this page: https://en.wikipedia.org/wiki/Affine_transformation

I says that if I would like to reflect an image, I can set the affine matrix to be [[-1, 0, 0], [0, 1, 0], [0, 0, 1]], but when I tried this code:

im = cv2.imread(imgpth)
im = cv2.resize(im, (1024, 512))
H, W, _ = im.shape

cv2.imshow('org', im)
M = np.float32([[-1, 0, 0], [0, 1, 0]])
aff = cv2.warpAffine(im, M, (W, H))
cv2.imshow('affine', aff)
cv2.waitKey(0)

I did not an flipped version of the image, instead the image is turned into a whole black image. What is wrong with my code ?


Solution

  • Your result image shouldn't be entirely black; the first column of your result image has some meaningful values, hasn't it? Your approach is correct, the image is flipped horizontally, but it's done with respect to the "image's coordinate system", i.e. the image is flipped along the y axis, and you only see the most right column of the flipped image. So, you just have to add a translation in x direction.

    Let's have a look at the following code:

    # Load image, get shape
    img = cv2.imread('rEC3E.png')
    H, W = img.shape[:2]
    
    # Flip horizontally
    M = np.float32([[-1, 0, W-1], [0, 1, 0]])   # Added translation of size W-1 in x direction
    affH = cv2.warpAffine(img, M, (W, H))
    
    # Flip vertically
    M = np.float32([[1, 0, 0], [0, -1, H-1]])   # Added translation of size H-1 in y direction
    affV = cv2.warpAffine(img, M, (W, H))
    
    # Outputs
    cv2.imshow('org', img)
    cv2.imshow('flip horizontally', affH)
    cv2.imshow('flip vertically', affV)
    cv2.waitKey(0)
    

    That's the input image:

    Input

    That's the horizontally flipped image:

    Horizontally flipped

    That's the vertically flipped image:

    enter image description here

    For this very basic operations, setting up the transformation matrix manually might be not difficult, but for everything beyond, you should have a look at getAffineTransform, and one or two tutorials on that. Setting up rotations, etc. might become difficult.

    Hope that helps!