Python OpenCV中的resize()函数的使用

时间:2022-09-19 13:24:48

改变图像大小意味着改变尺寸,无论是单独的高或宽,还是两者。也可以按比例调整图像大小。

这里将介绍resize()函数的语法及实例。

语法

函数原型

?
1
cv2.resize(src, dsize[, dst[, fx[, fy[, interpolation]]]])

参数:

 

参数 描述
src 【必需】原图像
dsize 【必需】输出图像所需大小
fx 【可选】沿水平轴的比例因子
fy 【可选】沿垂直轴的比例因子
interpolation

【可选】插值方式

 

【可选】插值方式

其中插值方式有很多种:

 

cv.inter_nearest 最近邻插值
cv.inter_linear 双线性插值
cv.inter_cubic 双线性插值
cv.inter_area 使用像素区域关系重新采样。它可能是图像抽取的首选方法,因为它可以提供无莫尔条纹的结果。但是当图像被缩放时,它类似于inter_nearest方法。

 

通常的,缩小使用cv.inter_area,放缩使用cv.inter_cubic(较慢)和cv.inter_linear(较快效果也不错)。默认情况下,所有的放缩都使用cv.inter_linear。

例子

保留高宽比

以下是我们将在其上进行实验的尺寸(149,200,4)(高度,宽度,通道数)的原始图像:

Python OpenCV中的resize()函数的使用

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import cv2
 
img = cv2.imread('./pictures/python.png', cv2.imread_unchanged)
 
print('original dimensions : ',img.shape)
 
scale_percent = 60  # percent of original size
width = int(img.shape[1] * scale_percent / 100)
height = int(img.shape[0] * scale_percent / 100)
dim = (width, height)
# resize image
resized = cv2.resize(img, dim, interpolation = cv2.inter_area)
 
print('resized dimensions : ',resized.shape)
 
cv2.imshow("resized image", resized)
cv2.waitkey(0)
cv2.destroyallwindows()

结果:

original dimensions : (149, 200, 4)
resized dimensions : (89, 120, 4)

Python OpenCV中的resize()函数的使用

调节scale_percent可以放大或缩小。需要准备shape先高再宽,参数是先宽再高。

还有一种方式,就是使用自带的参数fx和fy,更加方便。

?
1
2
3
4
5
6
7
8
9
10
import cv2
img = cv2.imread("./pictures/python.png")
print('original dimensions : ', img.shape)
 
resized = cv2.resize(img, none, fx=0.6, fy=0.6, interpolation=cv2.inter_area)
 
print('resized dimensions : ',resized.shape)
 
cv2.imshow("resized_img", resized)
cv2.waitkey(0)

不保留高宽比

例如,改变宽度,高度不变:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import cv2
 
img = cv2.imread("./pictures/python.png")
 
print('original dimensions : ',img.shape)
 
width = 440
height = img.shape[0] # keep original height
dim = (width, height)
 
# resize image
resized = cv2.resize(img, dim, interpolation = cv2.inter_area)
 
print('resized dimensions : ',resized.shape)
 
cv2.imshow("resized image", resized)
cv2.waitkey(0)
cv2.destroyallwindows()

结果:

original dimensions : (149, 200, 4)
resized dimensions : (149, 440, 4)

Python OpenCV中的resize()函数的使用

指定高和宽

给定高和宽的像数值。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import cv2
 
img = cv2.imread("./pictures/python.png")
 
print('original dimensions : ',img.shape)
 
width = 350
height = 450
dim = (width, height)
 
# resize image
resized = cv2.resize(img, dim, interpolation = cv2.inter_area)
 
print('resized dimensions : ',resized.shape)
 
cv2.imshow("resized image", resized)
cv2.waitkey(0)
cv2.destroyallwindows()

结果:

original dimensions : (149, 200, 4)
resized dimensions : (450, 350, 4)

Python OpenCV中的resize()函数的使用

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/lfri/p/10596530.html