Numpy 调整大小/重新缩放图像 [英] Numpy Resize/Rescale Image

查看:124
本文介绍了Numpy 调整大小/重新缩放图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拍摄一张图像并更改图像的比例,而它是一个 numpy 数组.

I would like to take an image and change the scale of the image, while it is a numpy array.

例如,我有一张可口可乐瓶的图片:bottle-1

For example I have this image of a coca-cola bottle: bottle-1

转换为形状为 (528, 203, 3) 的 numpy 数组,我想调整它的大小以表示第二个图像的大小:bottle-2

Which translates to a numpy array of shape (528, 203, 3) and I want to resize that to say the size of this second image: bottle-2

其形状为 (140, 54, 3).

如何在保持原始图像不变的情况下将图像的大小更改为特定形状?其他答案建议每隔一行或第三行剥离,但我想要做的基本上是通过图像编辑器但在 python 代码中缩小图像.在 numpy/SciPy 中是否有任何库可以执行此操作?

How do I change the size of the image to a certain shape while still maintaining the original image? Other answers suggest stripping every other or third row out, but what I want to do is basically shrink the image how you would via an image editor but in python code. Are there any libraries to do this in numpy/SciPy?

推荐答案

是的,你可以安装 opencv(这是一个用于图像处理和计算机视觉的库),并使用 cv2.resize 功能.例如使用:

Yeah, you can install opencv (this is a library used for image processing, and computer vision), and use the cv2.resize function. And for instance use:

import cv2
import numpy as np

img = cv2.imread('your_image.jpg')
res = cv2.resize(img, dsize=(54, 140), interpolation=cv2.INTER_CUBIC)

这里的 img 是一个包含原始图像的 numpy 数组,而 res 是一个包含 resized 图像的 numpy 数组.一个重要的方面是 interpolation 参数:有几种方法可以调整图像大小.特别是因为您缩小了图像,并且原始图像的大小不是调整后图像大小的倍数.可能的插值模式有:

Here img is thus a numpy array containing the original image, whereas res is a numpy array containing the resized image. An important aspect is the interpolation parameter: there are several ways how to resize an image. Especially since you scale down the image, and the size of the original image is not a multiple of the size of the resized image. Possible interpolation schemas are:

  • INTER_NEAREST - 最近邻插值
  • INTER_LINEAR - 双线性插值(默认使用)
  • INTER_AREA - 使用像素区域关系重采样.它可能是图像抽取的首选方法,因为它可以提供无摩尔纹结果.但是当图像放大时,它类似于INTER_NEAREST 方法.
  • INTER_CUBIC - 4x4 像素邻域上的双三次插值
  • INTER_LANCZOS4 - 8x8 像素邻域上的 Lanczos 插值
  • 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

与大多数选项一样,没有最佳"选项,因为对于每个调整大小的架构,都有一种策略优于另一种策略的情况.

Like with most options, there is no "best" option in the sense that for every resize schema, there are scenarios where one strategy can be preferred over another.

这篇关于Numpy 调整大小/重新缩放图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆