将边框添加到我的代码中的图像
问题描述:
帮助,我需要在下面的代码中显示的图像上放一个边框。我该怎么做呢?下面的代码拉起图像,现在我需要一个边框。帮助.. 所有这些代码是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()
答
只需创建一个稍大数组,它是黑色的,并与你的形象填补了中央像素。
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()
我在一类和刚学了这一切。我试图做类似的事情,它告诉我“图像”没有定义。我会通过使用这段代码获取这条消息吗?还是将这项工作?如果我确实收到这条消息,我该如何定义一个图像?那是一件事吗? – Anonymous
在你发布的代码片段中,没有变量'image',只有变量'img'。没有人可以帮助你:1)确切的代码+使用的任何数据(如图像文件),以及2)确切的错误消息。我发布的代码将与您发布的代码结合使用。只需将我的代码附加到您的代码段即可。 – Paul
我发布这个问题时的代码是我在程序中的所有代码。我已经添加了你的内容,现在它显示了我的图像,以及你的静态图像和带有边框的静态图像。我现在需要的只是用我的图像替换图像中的静态图像。我该怎么做呢? – Anonymous