图像处理

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

2020-10-15  本文已影响0人  lk311

1.图像缩放

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

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)

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
上一篇下一篇

猜你喜欢

热点阅读