引用原文链接:https://blog.csdn.net/Eastmount/article/details/82347501
一.图像缩放
import cv2
import numpy as np
import matplotlib.pyplot as plt
#读取图片
src = cv2.imread("C:/Users/31035/Desktop/yifei/01.jpg")
#图像缩放
result = cv2.resize(src, (200,100))
print(result.shape)
#显示图像
cv2.imshow("src", src)
cv2.imshow("result", result)
#等待显示
cv2.waitKey(0)
cv2.destroyAllWindows()
#fx、fy为系数
result = cv2.resize(src, None, fx=0.3, fy=0.3)
#显示图像
cv2.imshow("src", src)
cv2.imshow("result", result)
#等待显示
cv2.waitKey(0)
cv2.destroyAllWindows()
二、图像旋转
# 图像旋转主要调用getRotationMatrix2D()函数和warpAffine()函数实现,绕图像的中心旋转
# M = cv2.getRotationMatrix2D((cols/2, rows/2), 30, 1)
# 参数分别为:旋转中心、旋转度数、scale缩放图像
# rotated = cv2.warpAffine(src, M, (cols, rows))
# 参数分别为:原始图像、旋转参数、原始图像宽高
#原图的高、宽 以及通道数
rows, cols, channel = src.shape
M = cv2.getRotationMatrix2D((cols/2, rows/2), 30, 0.1)
rotated = cv2.warpAffine(src, M, (cols, rows))
#显示图像
cv2.imshow("src", src)
cv2.imshow("rotated", rotated)
#等待显示
cv2.waitKey(0)
cv2.destroyAllWindows()
三、图像翻转
# dst = cv2.flip(src, flipCode)
# 其中src表示原始图像,flipCode表示翻转方向,
# 如果flipCode为0,则以X轴为对称轴翻转,
# 如果fliipCode>0则以Y轴为对称轴翻转,如果flipCode<0则在X轴、Y轴方向同时翻转。
img = src
src = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
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(2,2,i+1), plt.imshow(images[i])
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
四、图像平移
#读取图片
img = cv2.imread("C:/Users/31035/Desktop/yifei/01.jpg",cv2.COLOR_BGR2RGB)
image = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)#方便plt展示
#图像平移 下、上、右、左平移
#x is width, y is height
M = np.float32([[1, 0, 100], [0, 1, 100]])
img1 = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))
M = np.float32([[1, 0, -100], [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(2,2,i+1), plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()