applying image decoration (border) in Python (programmatically) - python

I am looking for a way to create a border in python.Is there any library in Python which we can import to create a border.
Note that I do not want to use any image masks to create this effect (e.g. I don't want to use any image editing package like GIMP to create a border image mask) .
Here is what I am looking for:
import fooImageBorders
import Image
foo = Image.open("someImage.jpg")
foo2 = fooImageBorders.bevel(foo, color = black)
...I can write my own methods to add borders .. but if there is already something like this out there with a comprehensive set of border options, I would like to make use of it.
I looked at PIL documentation and couldn't find a way to do this. I have windows xp and there doesn't seem to be a way to install PythonMagick either for Python 2.6 if you don't have cygwin.

Look at the ImageOps module within the PIL.
import Image
import ImageOps
x = Image.open('test.png')
y = ImageOps.expand(x,border=5,fill='red')
y.save('test2.png')

You can use the PythonMagick module. the documentation for this module is here (Magic ++ documentation)
Example: To add a red 2 pixel border to an image, you need following code.
from PythonMagick import Image
i = Image('example.jpg') # reades image and creates an image instance
i.borderColor("#ff0000") # sets border paint color to red
i.border("2x2") # paints a 2 pixel border
i.write("out.jpg")
# writes the image to a file

foo2 = foo.copy()
draw = ImageDraw.Draw(foo2)
for i in range(width):
draw.rectangle([i, i, foo2.size[0]-i-1, foo2.size[1]-i-1], outline = color)
foo2 will have a width-pixel border of color.
If you want different colored borders on each side, you can replace .rectangle with repeated .line calls.
If you want the border not to cover any part of the existing image, use this instead of foo.copy().
foo2 = Image.new(foo.mode, (foo.size[0] + 2*width, foo.size[1] + 2*width))
foo2.paste(foo, (width, width))

Related

Crop image to circle shape for PyQt [duplicate]

This question already has answers here:
How to create circular image using pyqt4?
(3 answers)
How to crop an image using QPainterPath without saving rest of image
(2 answers)
Closed 1 year ago.
I am creating a simple application with PyQt6. I want to my code to automatically crop the selected image into circle shape. How can I do that? Please help
Using an external library like pillow or opencv makes things easy as they generally have functions that already provide similar processing, but there's no need to add a dependency for simple manipulations like this, unless performance becomes an issue.
On Qt it's pretty straightforward: create a new QPixmap based on the minimum extent (assuming the circle is going to be the biggest possible in a given rectangle), create a QPainterPath with a circle that will be used for clipping, and finally draw the source contents in it.
def circleImage(imagePath):
source = QtGui.QPixmap(imagePath)
size = min(source.width(), source.height())
target = QtGui.QPixmap(size, size)
target.fill(QtCore.Qt.transparent)
qp = QtGui.QPainter(target)
qp.setRenderHints(qp.Antialiasing)
path = QtGui.QPainterPath()
path.addEllipse(0, 0, size, size)
qp.setClipPath(path)
sourceRect = QtCore.QRect(0, 0, size, size)
sourceRect.moveCenter(source.rect().center())
qp.drawPixmap(target.rect(), source, sourceRect)
qp.end()
return target
This obviously creates an image with transparent background around the circle, you can use any of the global colors or your own QColor.
Note that, no matter the color, the fill() is mandatory, otherwise there will probably be random pixels on the unpainted portions of the image instead (usually some "RAM residue").

Is it possible to add a blue bar using PIL or Pillow?

So I have this grey bar
but I want to make a little part of it like this.
But I don't want to download the blue bar, I just want to make it with pure code using Python
I am not sure how you are really supposed to code it, but I thought if I draw a cyan-coloured circle at the right end of the progress bar, and then flood-fill behind it from the left, it should work:
#!/usr/bin/env python3
from PIL import Image, ImageDraw
# Open template and get drawing context
im = Image.open('progress.png').convert('RGB')
draw = ImageDraw.Draw(im)
# Cyan-ish fill colour
color=(98,211,245)
# Draw circle at right end of progress bar
x, y, diam = 254, 8, 34
draw.ellipse([x,y,x+diam,y+diam], fill=color)
# Flood-fill from extreme left of progress bar area to behind circle
ImageDraw.floodfill(im, xy=(14,24), value=color, thresh=40)
# Save result
im.save('result.png')
Just so you understand what I am doing, I draw a circle where the picture below is marked up in red, and then floodfill starting where the picture is marked up in yellow:
So, if you want more progress shown, just increase x in the code - if you want less progress, decrease x.
As regards the quality of the rounded ends, you are bound to get jaggy edges if you start with a circle of radius 17 and them scale it up. Here's what ImageMagick does, on the left with anti-aliasing and on the right without:
Keywords: Python, image processing, PIL, Pillow, progress, bar, progress-bar, rounded ends.

How to properly scale/rotate images in pyqtgraph?

I have implemented pyqtgraph inside QGraphicsView in PyQt5. When I display the image the following way, it is stretched out and expands in the same aspect ratio as the screen. How do I fix this?
image = pg.ImageItem(asarray(Image.open('pic.png')) )
self.graphicsView.addItem(image)
image.rotate(270)
EDIT: found out how to rotate image, so I updated question with the solution. Now I am just trying to scale it properly.
You probably want something like:
import pyqtgraph as pg
from PIL import Image
from numpy import asarray
app = pg.mkQApp()
# Set up a window with ViewBox inside
gv = pg.GraphicsView()
vb = pg.ViewBox()
gv.setCentralItem(vb)
gv.show()
# configure view for images
vb.setAspectLocked()
vb.invertY()
# display image
img_data = asarray(Image.open('/home/luke/tmp/graph.png'))
image = pg.ImageItem(img_data, axisOrder='row-major')
vb.addItem(image)
The important pieces here that set the image scaling/orientation are:
using ImageItem(axisOrder='row-major') because image files are stored in row-major order
vb.invertY() because image files have the +y axis pointing downward
and vb.setAspectLocked() to keep the pixels square
I used np.rot90() instead, it's much faster and cythonable
image = pg.ImageItem(np.rot90(np.asarray(Image.open('pic.png'))))

How to make simple graphs in python 2.7

I would like to make simple graphs for my web page in python/django, but I do not know, which library (and how) to use.
I DO NOT WANT CHARTS, I SEEK A WAY TO CREATE IMAGE FROM PRIMITIVES LIKE RECTANGLES.
Each such graph is probabely generated and used only one time, as next time the values would differ.
I can simply compute the positions of all rectangles, lines or texts in it, so I would like something lightweight to just create pictre from that, which I would return as img/png (or so) mime style
like <img src="http://my.web.www/my/page/graph" > where the parameters to show would be decidied by session and database.
I can compute all the sizes beforehand, so I would like something simple like
img=Image(PNG,598,89) # style, x, y
img.add_text('1.3.', 10,10)
img.add_rectagle(20,10, 70,20, CYAN, BLACK)
....
return img.render()
Can you direct me, how to do it?
Thanks beforehand
navit nailed it :)
# from django.utils.httpwrappers import HttpResponse
from PIL import Image, ImageDraw
import os,sys
im = Image.new('RGB',(598,89),'white')
draw = ImageDraw.Draw(im)
draw.rectangle((0,0,im.size[0]-1,im.size[1]-1), outline='blue')
draw.rectangle((25,10,590,20), fill='white', outline='black')
draw.rectangle((25,10,70,20), fill='rgb(255,0,0)', outline='black')
draw.rectangle((70,10,90,20), fill='green', outline='black')
draw.text((1,10),'1.3.',fill='black')
del draw
# write to stdout
im.save(sys.stdout, "PNG")
# draw.flush()
# response = HttpResponse(mimetype="image/png")
# image.save(response, "PNG")
# return response
You should check Pillow out. Here is a sample how it works:
from PIL import Image, ImageDraw
im = Image.open("lena.pgm")
draw = ImageDraw.Draw(im)
draw.line((0, 0) + im.size, fill=128)
draw.line((0, im.size[1], im.size[0], 0), fill=128)
del draw
# write to stdout
im.save(sys.stdout, "PNG")
Serving a file from Pillow to your client should be straightforward. Let me know if you have a question.
edit: found these examples to get you started.
http://matplotlib.org/ permits to generate plenty of great graphs. You should be able to save it as an image and integrate it to your webpage
What about plotly? Never used in a project, but by reading the examples it seems very powerful and easy to use. It has a static image export (as most graphic libraries probably have).

Python svgwrite module background color

I am using the svgwrite module in my Python code and I would like to set a background color. So far I have not been able to find anything. Is there a way to do it?
I was hoping for something during the initialization:
import svgwrite
canvas = svgwrite.drawing.Drawing(fill="#225566") # or background="#225566", or sth similar
canvas.save('image.png')
Or I could probably draw rectangle all over the place, but that's just weird.
It seems that svg itself does not define how to set the background colour. For svgwrite I use this:
svg_size_width = 900
svg_size_height = 4500
dwg = svgwrite.Drawing(name, (svg_size_width, svg_size_height), debug=True)
dwg.add(dwg.rect(insert=(0, 0), size=('100%', '100%'), rx=None, ry=None, fill='rgb(50,50,50)'))
dwg.save()

Categories

Resources