我使用的是python 3和最新版本的openCV.我试图使用提供的调整大小功能调整图像大小,但调整大小后图像非常扭曲.代码:

import cv2
file = "/home/tanmay/Desktop/test_image.png"
img = cv2.imread(file , 0)
print(img.shape)
cv2.imshow('img' , img)
k = cv2.waitKey(0)
if k == 27:
    cv2.destroyWindow('img')
resize_img = cv2.resize(img  , (28 , 28))
cv2.imshow('img' , resize_img)
x = cv2.waitKey(0)
if x == 27:
    cv2.destroyWindow('img')

原始图像为480 x 640(RGB,因此我通过0将其转换为灰度)

有没有什么方法可以使用OpenCV或任何其他库来调整它的大小并避免失真?我打算做一个手写数字识别器,我已经用MNIST数据训练了我的神经网络,因此我需要的图像是28x28.

推荐答案

你可以在下面试试.该函数将保持原始图像的纵横比.

def image_resize(image, width = None, height = None, inter = cv2.INTER_AREA):
    # initialize the dimensions of the image to be resized and
    # grab the image size
    dim = None
    (h, w) = image.shape[:2]

    # if both the width and height are None, then return the
    # original image
    if width is None and height is None:
        return image

    # check to see if the width is None
    if width is None:
        # calculate the ratio of the height and construct the
        # dimensions
        r = height / float(h)
        dim = (int(w * r), height)

    # otherwise, the height is None
    else:
        # calculate the ratio of the width and construct the
        # dimensions
        r = width / float(w)
        dim = (width, int(h * r))

    # resize the image
    resized = cv2.resize(image, dim, interpolation = inter)

    # return the resized image
    return resized

下面是一个用法示例.

image = image_resize(image, height = 800)

希望这有帮助.

Python-3.x相关问答推荐

根据样本量随机 Select 组内样本

我没有';无法理解此TemplateDoesNotExist错误

添加任意数量的 pandas 数据框

try 使用 GEKKO 求解非线性方程组.系统有多种解决方案,但 GEKKO 给出了错误的解决方案.我该如何解决?

如何沿单列获取嵌套列表中的唯一值?

无法理解此递归函数的分配和环境用法

嵌套协议的使用(协议成员也是协议)

使用 Python 在特定组的列中设置上限

安装没有 sudo 权限的 python3 和 pip3

使用 pandas 数据帧映射到中转( node )点的跨容量请求

Tkinter IntVar 返回 PY_VAR0 而不是值

ImportError:没有名为资源的模块

Pandas 将列格式化为货币

在带有 M1 芯片(基于 ARM 的 Apple Silicon)的 Mac 上安装较早版本的 Python(3.8 之前)失败

Python 3 变量名中接受哪些 Unicode 符号?

为什么`multiprocessing.Queue.get`这么慢?

为 True 相交两个布尔数组

类型提示返回 NameError: name 'datetime' not defined

如何使用请求发送带有标头的 PATCH 请求

用 Anaconda 安装了一个包,无法在 Python 中导入