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

Vee*_*eer 5 python image-processing python-imaging-library python-3.x

我用过 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
Run Code Online (Sandbox Code Playgroud)

我需要在图像的所有 4 个边上为图像添加一个边框

Mar*_*ell 6

我建议使用 PIL 的内置expand()函数,它允许您为图像添加任何颜色和宽度的边框。

所以,从这个开始:

在此处输入图片说明

#!/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')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


如果你想从左右的顶部/底部有不同大小的边框,给两个宽度:

bordered = ImageOps.expand(im, border=(10,50), fill=(0,0,0)) 
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


如果你想在所有边上有不同大小的边框,给 4 个宽度:

bordered = ImageOps.expand(im, border=(10,40,80,120), fill=(0,0,0))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

关键词:PIL、枕头、ImageOps、Python、边框、边框、边框外、添加边框、扩展、填充、范围、图像、图像处理。


Ben*_*tte 1

这是您需要更改的内容,以使边框具有任意数量的 px 宽:

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)
Run Code Online (Sandbox Code Playgroud)

#other 3 boxes不做#primary box方框,而是分别得 3 分和 1 分。