Why I cannot flip an image with opencv affine transform?

二次信任 提交于 2020-03-25 22:14:42

问题


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 ?


回答1:


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:

That's the horizontally flipped image:

That's the vertically flipped image:

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!



来源:https://stackoverflow.com/questions/57863376/why-i-cannot-flip-an-image-with-opencv-affine-transform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!