在python中创建具有一定宽度边框的图像

时间:2019-02-15 03:58:48

标签: python python-3.x image-processing python-imaging-library

我用过PIL

#back_color_width 

for x in range(w):
    for y in range(h):
        if x==0 or y==0 or x==w-1 or y==h-1 :
            pixels[x,y] = back_color

我需要在图像上添加边框,并在图像的所有4边上都设置宽度

4 个答案:

答案 0 :(得分:2)

我建议使用PIL内置的expand()功能,该功能可让您向图像添加任何颜色和宽度的边框。

因此,从此开始:

enter image description here

#!/usr/bin/env python3

from PIL import Image, ImageOps

# Open image
im = Image.open('start.png')

# Add border and save
bordered = ImageOps.expand(im, border=10, fill=(0,0,0))

bordered.save('result.png')

enter image description here


如果您想从左至右在顶部/底部使用不同大小的边框,请提供两个宽度:

bordered = ImageOps.expand(im, border=(10,50), fill=(0,0,0)) 

enter image description here


如果要在所有面上使用不同大小的边框,请提供4种宽度:

bordered = ImageOps.expand(im, border=(10,40,80,120), fill=(0,0,0))

enter image description here

关键字:PIL,枕头,ImageOps,Python,边框,边框,外部边框,添加边框,展开,图像,图像处理。

答案 1 :(得分:1)

您需要进行以下更改以使边框的像素宽度达到任意数量:

for x in range(w):
    for y in range(h):
        if (x<border_width
            or y<border_width 
            or x>w-border_width-1 
            or y>h-border_width-1):
            pixels[x,y] = (0,0,0)

#other 3 boxes#primary box不在框内,而是分别为3点和1点。

答案 2 :(得分:1)

您真的很亲密!您只需要更改第一个if语句。现在您确实有一个边框,但是边框的所有侧面均为1像素宽。也许更改为

if x<back_color_width or y<back_color_width or x > w+ back_color_width or y > w+back_color_width:
    pixel[x,y]=back_color

答案 3 :(得分:0)

如果我了解您的意思,我认为解决方法如下:

import numpy as np

def create_border(img, width, color = np.array([0,0,0]) ):
    #color must be a np.array

    img_shape = img.shape
    upper_border = np.full((width, img_shape[1], 3), color) #for 3-channel image
    side_border = np.full((img_shape[0] + 2*width, width, 3), color)

    bordered = np.concatenate([upper_border, img, upper_border])        
    bordered = np.concatenate([side_border, bordered, side_border], axis=1)

    return bordered