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

元画像は×640 480(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)

説明: 機能は、任意のサイズの入力を受け取り、入力画像の高さよりも大きなサイズの二乗形状ブランク画像を生成し幅。 次に、元のイメージをブランクイメージの中央に置きます。この正方形の画像を所望のサイズにリサイズして、元の画像コンテンツの形状が保存されるようにする。

希望、これは歪みなくあなた

関連する問題