OpenCV图片沿对角线调换
1、在学习左上角和右下角对调之前,我们有必要了解一下什么是水平方向对调图片和竖直方向对调图片。
2、在开始图片对调之前,我们思考一下这个问题
我们将A1和B7进行互换,A2和B6进行互换,以此类推,将A组元素和B组元素对角线互换,得到新的A和B,我们对图片进行的对角线调换也是这个原理。
3、代码实现:
import cv2 as cv
import numpy as np
# 要进行调换的图片
img = cv.imread("D:/img/pic (1).png",1)
# 获取图片基本信息
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
mode = imgInfo[2]
# 获取原图的第一个镜像为了下面以横轴为主进行调换操作
dst1 = np.zeros(imgInfo,np.uint8)
np.copyto(dst1,img)
# 获取原图的第二个镜像为了下面以横轴为主进行调换操作
dst2 = np.zeros(imgInfo,np.uint8)
np.copyto(dst2,img)
# 展示原图像
cv.imshow("img",img)
# 以横轴为主进行图像对角调换
for i in range(0,width):
# 此处的分界点是竖直方向的一半
for j in range(0,int(height/2)):
dst1[i][j] += dst1[width-1-i][height-1-j]
dst1[width-1-i][height-1-j] = dst1[i][j] - dst1[width-1-i][height-1-j]
dst1[i][j] -= dst1[width-1-i][height-1-j]
# 以纵轴为主进行对角调换
for i in range(0,height):
# 此处的分界点是水平方向的一半
for j in range(0,int(width/2)):
dst2[i][j] += dst2[width-1-i][height-1-j]
dst2[width-1-i][height-1-j] = dst2[i][j] - dst2[width-1-i][height-1-j]
dst2[i][j] -= dst2[width-1-i][height-1-j]
# 展示调换后的图一和图二
cv.imshow("dst1",dst1)
cv.imshow("dst2",dst2)
cv.waitKey(0)
cv.destroyAllWindows()
上述代码运行结果如下图所示:
总结,从简单的换位置思考这个问题更容易上手,此图和该图旋转360度得到的图像应该是一直的。