I have used 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
I need to add a border to the image with a width on all 4 sides of image
To add borders to the images OpenCV has a package copyMakeBorder which helps to make a border around the image. Parameters of copyMakeBorder: inputImage. topBorderWidth.
The border () function is an inbuilt function in the Python Wand ImageMagick library which is used to apply the border around the image. Parameters: This function accepts three parameters as mentioned above and defined below: Color: This parameter is used to specify the value of color which is a string type variable.
The border () function is an inbuilt function in the Python Wand ImageMagick library which is used to apply the border around the image.
We can clearly see the borders are been added/drawn. For the grayscale image, though we have mentioned pink, a black border is drawn. When we talk about the border, it is basically a constant pixel value of one color around the entire image. It is important to take note of the thickness of the border to be able to see.
This is because the length of the shape of the image matrix would be 2. Therefore we cannot add a color border whose color value would be of size 3 and thus it cannot be mapped easily. If the image is read in RGB, we can have a choice to pick the color for the border. This is because the length of the shape of the image matrix would be 3.
I would recommend using PIL's built-in expand()
function, which allows you to add a border of any colour and width to an image.
So, starting with this:
#!/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')
If you want different sized borders on the top/bottom from the left-right, give two widths:
bordered = ImageOps.expand(im, border=(10,50), fill=(0,0,0))
If you want different sized borders on all sides, give 4 widths:
bordered = ImageOps.expand(im, border=(10,40,80,120), fill=(0,0,0))
Keywords: PIL, Pillow, ImageOps, Python, border, bordering, border outside, add border, expand, pad, extent, image, image processing.
This is what you need to change to make the border any number of px wide:
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
and #primary box
Doesn't make boxes but instead 3 points and 1 point respectively.
You are really close! You just need to change the first if
statement. Right now you do have a border, but the border is 1 pixel wide on all sides. Maybe change to
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With