2017-04-06 54 views
1

幫助,我需要在下面的代碼中顯示的圖像上放一個邊框。我該怎麼做呢?下面的代碼拉起圖像,現在我需要一個邊框。幫助.. 所有這些代碼是Python的將邊框添加到我的代碼中的圖像

# -*- coding: utf-8 -*- 
''' 
LoganCaroline_1_4_7: Merge images 
''' 
import matplotlib.pyplot as plt 
import os.path 
import numpy as np  # 「as」 lets us use standard abbreviations 

'''Read the image data''' 
# Get the directory of this python script 
directory = os.path.dirname(os.path.abspath(__file__)) 
# Build an absolute filename from directory + filename 
filename = os.path.join(directory, 'family1.jpg') 
# Read the image data into an array 
img = plt.imread(filename) 

'''Show the image data''' 
# Create figure with 1 subplot 
fig, ax = plt.subplots(1, 1) 
# Show the image data in a subplot 
ax.imshow(img, interpolation='none') 
# Show the figure on the screen 
fig.show() 

回答

1

只需創建一個稍大數組,它是黑色的,並與你的形象填補了中央像素。

import numpy as np 
import matplotlib.pyplot as plt 

def frame_image(img, frame_width): 
    b = frame_width # border size in pixel 
    ny, nx = img.shape[0], img.shape[1] # resolution/number of pixels in x and y 
    if img.ndim == 3: # rgb or rgba array 
     framed_img = np.zeros((b+ny+b, b+nx+b, img.shape[2])) 
    elif img.ndim == 2: # grayscale image 
     framed_img = np.zeros((b+ny+b, b+nx+b)) 
    framed_img[b:-b, b:-b] = img 
    return framed_img 

img = np.random.rand(456, 333, 3) 
fig, (ax1, ax2) = plt.subplots(1,2) 
ax1.imshow(img, interpolation='none') 
ax2.imshow(frame_image(img, 20), interpolation='none') 
plt.show() 

enter image description here

+0

我在一類和剛學了這一切。我試圖做類似的事情,它告訴我「圖像」沒有定義。我會通過使用這段代碼獲取這條消息嗎?還是將這項工作?如果我確實收到這條消息,我該如何定義一個圖像?那是一件事嗎? – Anonymous

+0

在你發佈的代碼片段中,沒有變量'image',只有變量'img'。沒有人可以幫助你:1)確切的代碼+使用的任何數據(如圖像文件),以及2)確切的錯誤消息。我發佈的代碼將與您發佈的代碼結合使用。只需將我的代碼附加到您的代碼段即可。 – Paul

+0

我發佈這個問題時的代碼是我在程序中的所有代碼。我已經添加了你的內容,現在它顯示了我的圖像,以及你的靜態圖像和帶有邊框的靜態圖像。我現在需要的只是用我的圖像替換圖像中的靜態圖像。我該怎麼做呢? – Anonymous