2017-06-20 323 views
2

我正在使用python 3和最新版本的openCV。我正在尝试使用提供的调整大小功能调整图像大小,但调整大小后图像非常失真。代码:调整图像的大小而不失真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 * 640(RGB因此我通过0得到它的灰度)

有什么办法,我可以调整它的大小和使用OpenCV的或任何其他避免失真图书馆呢?我打算做一个手写数字识别器,并且我已经使用MNIST数据训练了我的神经网络,因此我需要该图像为28x28。

+3

没有任何失真,你有2个选项:a)图像的作物部位,使其相同的纵横比。 b)将图像的一部分(例如黑色像素)添加到图像的侧面以使其具有相同的纵横比。如果你没有相同的长宽比,就不可能不失真地获得它。 – api55

+0

您必须确保您传递的新尺寸的纵横比与原始图像相同,并确保使用合适的插值方法 –

+0

我向原始图像添加了黑色像素,使其成为640x640,但仍然在调整尺寸时我得到一个扭曲的图像。我能做什么 ? –

回答

9

您可以在下面尝试。该功能将保持原始图像的纵横比。

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) 

希望这会有所帮助。

+0

如果我想改变原始图像的宽高比,该怎么办?无论原始尺寸如何,我都希望每张图片都能达到28x28。 –

+1

然后,直接使用'cv2.resize(image,(28,28),interpolation = inter)'。 – thewaywewere

+1

@TanmayBhatnagar如果我的答案有助于解决您的问题,您还可以给我一个投票吗? – thewaywewere

0

在使用opencv的python中试试这个简单的函数。只是传递图像,并提及你想要的广场的大小。

def get_square(image,square_size): 

    height,width=image.shape 
    if(height>width): 
     differ=height 
    else: 
     differ=width 
    differ+=4 

    mask = np.zeros((differ,differ), dtype="uint8") 
    x_pos=int((differ-width)/2) 
    y_pos=int((differ-height)/2) 
    mask[y_pos:y_pos+height,x_pos:x_pos+width]=image[0:height,0:width] 
    mask=cv2.resize(jk,(square_size,square_size),interpolation=cv2.INTER_AREA) 

    return mask 

用法: squared_image = get_square(图像,28)

解释: 函数采用任意大小的输入和它创建尺寸比输入图像的高度大的平方形状空白图像和宽度。然后它将原始图像放在空白图像的中心。然后将此方形图像调整为所需的大小,以保留原始图像内容的形状。

希望,这将帮助你