2017-06-20 324 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)

解釋: 函數採用任意大小的輸入和它創建尺寸比輸入圖像的高度大的平方形狀空白圖像和寬度。然後它將原始圖像放在空白圖像的中心。然後將此方形圖像調整爲所需的大小,以保留原始圖像內容的形狀。

希望,這將幫助你