调整图像大小而不失真OpenCV [英] Resize an image without distortion OpenCV

查看:4461
本文介绍了调整图像大小而不失真OpenCV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using python 3 and latest version of openCV. I am trying to resize an image using the resize function provided but after resizing the image is very distorted. Code :

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使其达到灰度)

The original image is 480 x 640 (RGB therefore i passed the 0 to get it to grayscale)

有没有办法我可以使用OpenCV或任何其他库来调整大小并避免失真吗?我打算制作一个手写数字识别器,我使用MNIST数据训练我的神经网络,因此我需要图像为28x28。

Is there any way i could resize it and avoid the distortion using OpenCV or any other library perhaps? I intend to make a handwritten digit recogniser and i have trained my neural network using the MNIST data therefore i need the image to be 28x28.

推荐答案

您可以尝试以下。该函数将保持原始图像的宽高比。

You may try below. The function will keep the aspect rate of the original image.

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)

希望这会有所帮助。

这篇关于调整图像大小而不失真OpenCV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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