本节实现的是使用OpenCV里自带的函数,对图像进行简单的几何变换。
不再赘述。
import cv2
import numpy as np
# read the original
img = cv2.imread('../test2.jpg')
cv2.imshow('original', img)
利用OpenCV自带的resize()函数实现放大与缩小。其声明为:
cv2.resize(src, dsize[, dst[, fx[, fy[, interpolation]]]]) → dst
其中各个参数的意义如下:
参数 | 意义 |
---|---|
INTER_NEAREST | a nearest-neighbor interpolation |
INTER_LINEAR | a bilinear interpolation (used by default) |
INTER_AREA | resampling using pixel area relation. It may be a preferred method for image decimation, as it gives moire’-free results. But when the image is zoomed, it is similar to the INTER_NEAREST method. |
INTER_CUBIC | a bicubic interpolation over 4x4 pixel neighborhood |
INTER_LANCZOS4 | a Lanczos interpolation over 8x8 pixel neighborhood |
本文将原图放大至原来的2倍。
# expand
rows, cols, channels = img.shape
img_ex = cv2.resize(img, (2*cols, 2*rows), interpolation=cv2.INTER_CUBIC)
cv2.imshow('expand', img_ex)
这里将原图缩小为原来的一半。
# zoom
img_zo = cv2.resize(img, (cols/2, rows/2), interpolation=cv2.INTER_AREA)
cv2.imshow('zoom', img_zo)
平移可以由平移矩阵描述:
其中
# trans
M = np.array([[1, 0, 50],[0, 1, 50]], np.float32)
img_tr =cv2.warpAffine(img, M, img.shape[:2])
cv2.imshow('trans', img_tr)
其中warpAffine()的声明如下:
cv2.warpAffine(src, M, dsize[, dst[, flags[, borderMode[, borderValue]]]]) → dst
各个参数的意义如下:
利用getRotationMatrix2D()获得旋转矩阵,其声明为
cv2.getRotationMatrix2D(center, angle, scale) → retval
各个参数的意义:
然后再利用warpAffine()函数进行变换。
# Rotation
M=cv2.getRotationMatrix2D((cols/2,rows/2), 45, 1)
img_ro =cv2.warpAffine(img, M, img.shape[:2])
cv2.imshow('rotation', img_ro)
程序的源代码如下:
# created by Huang Lu
# 2016/8/26 17:35
# Department of EE, Tsinghua Univ.
import cv2
import numpy as np
# read the original
img = cv2.imread('../test2.jpg')
cv2.imshow('original', img)
# expand
rows, cols, channels = img.shape
img_ex = cv2.resize(img, (2*cols, 2*rows), interpolation=cv2.INTER_CUBIC)
cv2.imshow('expand', img_ex)
# zoom
img_zo = cv2.resize(img, (cols/2, rows/2), interpolation=cv2.INTER_AREA)
cv2.imshow('zoom', img_zo)
# trans
M = np.array([[1, 0, 50],[0, 1, 50]], np.float32)
img_tr =cv2.warpAffine(img, M, img.shape[:2])
cv2.imshow('trans', img_tr)
# Rotation
M=cv2.getRotationMatrix2D((cols/2,rows/2), 45, 1)
img_ro =cv2.warpAffine(img, M, img.shape[:2])
cv2.imshow('rotation', img_ro)
# wait the key and close windows
cv2.waitKey(0)
cv2.destroyAllWindows()
也可以参考我的GitHub上的,点击这里。
在命令行进入该源程序所在目录后,运行python main.py
后即可显示结果。显示结果如下: