python - 调整图像大小而不失真 OpenCV

标签 python image python-3.x opencv

我正在使用 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 - 调整图像大小而不失真 OpenCV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44650888/

相关文章:

python - 尝试在 python 中实现简单的 BFS...如果搜索成功则无法打印值

python - 如何使用 plotly 绘制梯度下降

python - Flask SQLAlchemy 获取所有 json

c# - 如何将 “ContentType= {image/jpeg}” 的响应保存为图像 C#?

python - 单击 QTextDocument 中的链接生成自定义事件

python - Plotly:plotly 表达遵循什么颜色循环?

javascript - 将大图像站点转换为 html/css/javascript 的最简单方法?

java - Spring + JSF - 从数据库检索图像并在浏览器中显示

python - 删除 Python(希伯来语)中从右到左的字符\u200f

python - Python 中的 yield 问题 |使用辅助函数