python - 在我的代码中添加边框和图像

标签 python image border

帮助,我需要在下面代码显示的图像上添加边框。我该怎么做呢?下面的代码提取图像,现在我需要一个边框。帮助..所有这些代码都是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()

enter image description here

关于python - 在我的代码中添加边框和图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43261338/

相关文章:

html - 背景图像 CSS 的最大尺寸

swift - 如何创建看起来像用 Swift 铅笔绘制的 View 边框?

python - 在多列 pandas 上应用 "list"函数

python - 用嵌套循环填充二维列表会跳过并在 python 中意外地重复值

image - 检测灰度或二值图像中的六边形形状

wpf - 为每个角的边框设置不同的画笔颜色

r - 在线图周围插入边框

随机数生成器的 Python 代码未按预期打印

python - 使用一行访问 Pandas 数据框中的数据

html - 混合内容(图像/文本)在 Div 中调整大小