OpenCV 提供了函数 cv2.resize() 用于调整图像大小。OpenCV中的调整大小被称为 缩放 。我们可以通过指定图像大小或缩放因子来调整图像大小。当我们指定缩放因子时,宽高比会得到保留。

cv2.resize() 函数中有不同的插值方法:

cv2.INTER_AREA —— 用于缩小图像。cv2.INTER_CUBIC —— 慢速,用于缩放。cv2.INTER_LINEAR —— 用于缩放。它是所有调整大小目的的默认方法。

步骤

您可以使用以下步骤来调整图像大小:

导入所需的库。在以下所有Python示例中,所需的Python库是 OpenCV 和 Matplotlib 。确保您已经安装它们。

import cv2

import matplotlib.pyplot as plt

使用 cv2.imread() 函数读取图像。指定带有图像类型的完整图像路径(.jpg或.png)。

img = cv2.imread('birds.jpg')

传递 new_size 或 scaling factors fx and fy 和 interpolation 来调整图像大小。 fx 和 fy 分别是宽度和高度的比例因子。

resize_img = cv2.resize(img, new_size)

resize_img = cv2.resize(img,(0, 0),fx=0.5, fy=0.7, interpolation = cv2.INTER_AREA)

显示调整大小后的图像。

plt.imshow(resize_img)

让我们通过一些Python示例来了解不同的图像调整大小选项。

我们将使用此图像作为以下示例中的 输入文件 :

示例1

在以下Python程序中,我们将输入图像的大小调整为 new_size = 450, 340 (即 width=450,height=340 )。

import cv2

import matplotlib.pyplot as plt

img = cv2.imread('birds.jpg')

h, w, c = img.shape

# Different scaling ratios

scaling_ratio = [0.1, 0.5, 2, 5]

# Different interpolations

interpolation = [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_AREA, cv2.INTER_CUBIC, cv2.INTER_LANCZOS4]

# Resize the image using different scaling ratios and interpolations

fig = plt.figure()

rows = len(scaling_ratio)

columns = len(interpolation)

count = 1

for i in range(rows):

for j in range(columns):

if count > rows*columns:

break

new_size = (int(w*scaling_ratio[i]), int(h*scaling_ratio[i]))

count += 1

resized_img = cv2.resize(img, new_size, interpolation[j])

resized_img = cv2.cvtColor(resized_img, cv2.COLOR_BGR2RGB)

fig.add_subplot(rows, columns, count).title(f"Scaling Ratio: {scaling_ratio[i]}, Interpolation: {interpolation[j]}")

plt.imshow(resized_img)

plt.show()

# 导入所需库

import cv2

import matplotlib.pyplot as plt

# 读取输入图像

img = cv2.imread('birds.jpg')

# 使用不同的插值调整图像大小

resize_cubic = cv2.resize(img,(0, 0),fx=2, fy=2, interpolation = cv2.INTER_CUBIC)

resize_area = cv2.resize(img,(0, 0),fx=0.5, fy=0.7, interpolation = cv2.INTER_AREA)

resize_linear = cv2.resize(img,(0, 0),fx=2, fy=2, interpolation = cv2.INTER_LINEAR)

# 显示原始图像和调整大小后的图像

plt.subplot(221),plt.imshow(img), plt.title("原始图像")

plt.subplot(222), plt.imshow(resize_cubic), plt.title("插值Cubic")

plt.subplot(223), plt.imshow(resize_area), plt.title("插值Area")

plt.subplot(224), plt.imshow(resize_linear), plt.title("插值Linear")

plt.show()

输出

运行以上程序,将生成以下输出−

为帮助更多对人工智能感兴趣的小伙伴们能够有效的系统性的学习以及论文的研究,小编特意制作整理了一份人工智能学习资料给大家,整理了很久,非常全面。

大致内容包括一些人工智能基础入门视频和文档+AI常用框架实战视频、计算机视觉、机器学习、图像识别、NLP、OpenCV、YOLO、pytorch、深度学习与神经网络等学习资料、课件源码、国内外知名精华资源、以及AI热门论文等全套学习资料。

需要以上这些文中提到的资料,请点击此处→【人工智能全套完整VIP资料】即可免费获取。

 

看完三件事❤️

如果你觉得这篇内容对你还蛮有帮助,我想邀请你帮我三个小忙:点赞,转发,有你们的 『点赞和评论』,才是我创造的动力。关注作者公众号 『 python深度学习NLP 』,不定期分享原创知识。关注后回复【666】扫码即可获取学习资料包。同时可以期待后续文章ing。  

 

 

参考阅读

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: