图片处理-opencv-3.图像缩放、旋转、翻转、平移

1.图像缩放

result = cv2.resize(src, dsize[, result[. fx[, fy[, interpolation]]]])

  • src表示原始图像
  • dsize表示缩放大小,fx和fy表示缩放倍数,dsize或fx\fy设置一个即可实现图像缩放
import cv2  
import numpy as np  

#读取图片
src = cv2.imread('data/test1.jpg')

#图像缩放
result = cv2.resize(src, (200,300))
print(result.shape)
result1 = cv2.resize(src, None, fx=0.5, fy=0.5)
print(result1.shape)

#显示图像
cv2.imshow("src", src)
cv2.imshow("result", result)
cv2.imshow("result1", result1)
#等待显示
cv2.waitKey(0)
cv2.destroyAllWindows()

2.图像旋转

图像旋转主要调用getRotationMatrix2D()函数和warpAffine()函数实现
M = cv2.getRotationMatrix2D(旋转中心, 旋转度数, scale)
rotated = cv2.warpAffine(原始图像, 旋转参数, 原始图像宽高)

import cv2  
import numpy as np  

#读取图片
src = cv2.imread('data/test1.jpg')

#原图的高、宽 以及通道数
rows, cols, channel = src.shape

#绕图像的中心旋转
#参数:旋转中心 旋转度数 scale
M = cv2.getRotationMatrix2D((cols/2, rows/2), 30, 1)

#参数:原始图像 旋转参数 元素图像宽高
rotated = cv2.warpAffine(src, M, (cols, rows))

#显示图像
cv2.imshow("src", src)
cv2.imshow("rotated", rotated)

#等待显示
cv2.waitKey(0)
cv2.destroyAllWindows()

3.图像翻转

dst = cv2.flip(src, flipCode)

  • src表示原始图像
  • flipCode表示翻转方向,如果flipCode为0,则以X轴为对称轴翻转,如果fliipCode>0则以Y轴为对称轴翻转,如果flipCode<0则在X轴、Y轴方向同时翻转
import cv2
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(15,8))

#读取图片
img = cv2.imread('data/test3.jpg')
src = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

#图像翻转
#0以X轴为对称轴翻转 >0以Y轴为对称轴翻转 <0X轴Y轴翻转
img1 = cv2.flip(src, 0)
img2 = cv2.flip(src, 1)
img3 = cv2.flip(src, -1)

#显示图形
titles = ['Source', 'Image1', 'Image2', 'Image3']
images = [src, img1, img2, img3]
for i in range(4):
   plt.subplot(1, 4, i + 1), plt.imshow(images[i], 'gray')
   plt.title(titles[i])
   plt.xticks([]), plt.yticks([])
plt.show()
image.png

4.图像平移

图像平移首先定义平移矩阵M,再调用warpAffine()函数实现平移

M = np.float32([[1, 0, x], [0, 1, y]])

shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))

import cv2
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(15,8))

#读取图片
img = cv2.imread('data/test3.jpg')
image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

#图像平移 下、上、右、左平移
M = np.float32([[1, 0, 0], [0, 1, 100]])
img1 = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))

M = np.float32([[1, 0, 0], [0, 1, -100]])
img2 = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))

M = np.float32([[1, 0, 100], [0, 1, 0]])
img3 = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))

M = np.float32([[1, 0, -100], [0, 1, 0]])
img4 = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))

#显示图形
titles = ['Image1', 'Image2', 'Image3', 'Image4']
images = [img1, img2, img3, img4]
for i in range(4):
   plt.subplot(1, 4, i + 1), plt.imshow(images[i], 'gray')
   plt.title(titles[i])
   plt.xticks([]), plt.yticks([])
plt.show()
image.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容