Python pil imagedraw line

ImageDraw Module¶

The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use.

For a more advanced drawing library for PIL, see the aggdraw module.

Example: Draw a gray cross over an image¶

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") 

Concepts¶

Coordinates¶

The graphics interface uses the same coordinate system as PIL itself, with (0, 0) in the upper left corner.

Colors¶

To specify colors, you can use numbers or tuples just as you would use with PIL.Image.Image.new() or PIL.Image.Image.putpixel() . For “1”, “L”, and “I” images, use integers. For “RGB” images, use a 3-tuple containing integer values. For “F” images, use integer or floating point values.

For palette images (mode “P”), use integers as color indexes. In 1.1.4 and later, you can also use RGB 3-tuples or color names (see below). The drawing layer will automatically assign color indexes, as long as you don’t draw with more than 256 colors.

Читайте также:  Количество элементов строки python

Color Names¶

See Color Names for the color names supported by Pillow.

Fonts¶

PIL can use bitmap fonts or OpenType/TrueType fonts.

Bitmap fonts are stored in PIL’s own format, where each font typically consists of a two files, one named .pil and the other usually named .pbm. The former contains font metrics, the latter raster data.

To load a bitmap font, use the load functions in the ImageFont module.

To load a OpenType/TrueType font, use the truetype function in the ImageFont module. Note that this function depends on third-party libraries, and may not available in all PIL builds.

Example: Draw Partial Opacity Text¶

from PIL import Image, ImageDraw, ImageFont # get an image base = Image.open('Pillow/Tests/images/lena.png').convert('RGBA') # make a blank image for the text, initialized to transparent text color txt = Image.new('RGBA', base.size, (255,255,255,0)) # get a font fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 40) # get a drawing context d = ImageDraw.Draw(txt) # draw text, half opacity d.text((10,10), "Hello", font=fnt, fill=(255,255,255,128)) # draw text, full opacity d.text((10,60), "World", font=fnt, fill=(255,255,255,255)) out = Image.alpha_composite(base, txt) out.show() 

Functions¶

Creates an object that can be used to draw in the given image.

Note that the image will be modified in place.

  • im – The image to draw in.
  • mode – Optional mode to use for color values. For RGB images, this argument can be RGB or RGBA (to blend the drawing into the image). For all other modes, this argument must be the same as the image mode. If omitted, the mode defaults to the mode of the image.

Methods¶

Draws an arc (a portion of a circle outline) between the start and end angles, inside the given bounding box.

  • xy – Four points to define the bounding box. Sequence of [(x0, y0), (x1, y1)] or [x0, y0, x1, y1] .
  • start – Starting angle, in degrees. Angles are measured from 3 o’clock, increasing clockwise.
  • end – Ending angle, in degrees.
  • fill – Color to use for the arc.

Draws a bitmap (mask) at the given position, using the current fill color for the non-zero portions. The bitmap should be a valid transparency mask (mode “1”) or matte (mode “L” or “RGBA”).

This is equivalent to doing image.paste(xy, color, bitmap) .

To paste pixel data into an image, use the paste() method on the image itself.

PIL.ImageDraw.Draw. chord ( xy, start, end, fill=None, outline=None ) ¶

Same as arc() , but connects the end points with a straight line.

  • xy – Four points to define the bounding box. Sequence of [(x0, y0), (x1, y1)] or [x0, y0, x1, y1] .
  • outline – Color to use for the outline.
  • fill – Color to use for the fill.

Draws an ellipse inside the given bounding box.

  • xy – Four points to define the bounding box. Sequence of either [(x0, y0), (x1, y1)] or [x0, y0, x1, y1] .
  • outline – Color to use for the outline.
  • fill – Color to use for the fill.

Draws a line between the coordinates in the xy list.

  • xy – Sequence of either 2-tuples like [(x, y), (x, y), . ] or numeric values like [x, y, x, y, . ] .
  • fill – Color to use for the line.
  • width – The line width, in pixels. Note that line joins are not handled well, so wide polylines will not look good.

Same as arc, but also draws straight lines between the end points and the center of the bounding box.

  • xy – Four points to define the bounding box. Sequence of [(x0, y0), (x1, y1)] or [x0, y0, x1, y1] .
  • outline – Color to use for the outline.
  • fill – Color to use for the fill.

Draws points (individual pixels) at the given coordinates.

  • xy – Sequence of either 2-tuples like [(x, y), (x, y), . ] or numeric values like [x, y, x, y, . ] .
  • fill – Color to use for the point.

The polygon outline consists of straight lines between the given coordinates, plus a straight line between the last and the first coordinate.

  • xy – Sequence of either 2-tuples like [(x, y), (x, y), . ] or numeric values like [x, y, x, y, . ] .
  • outline – Color to use for the outline.
  • fill – Color to use for the fill.
  • xy – Four points to define the bounding box. Sequence of either [(x0, y0), (x1, y1)] or [x0, y0, x1, y1] . The second point is just outside the drawn rectangle.
  • outline – Color to use for the outline.
  • fill – Color to use for the fill.

This method is experimental.

PIL.ImageDraw.Draw. text ( xy, text, fill=None, font=None, anchor=None ) ¶

Draws the string at the given position.

Return the size of the given string, in pixels.

Legacy API¶

The Draw class contains a constructor and a number of methods which are provided for backwards compatibility only. For this to work properly, you should either use options on the drawing primitives, or these methods. Do not mix the old and new calling conventions.

PIL.ImageDraw. ImageDraw ( image ) ¶

Return type: Draw

PIL.ImageDraw.Draw. setink ( ink ) ¶

Deprecated since version 1.1.5.

Sets the color to use for subsequent draw and fill operations.

PIL.ImageDraw.Draw. setfill ( fill ) ¶

Deprecated since version 1.1.5.

If the mode is 0, subsequently drawn shapes (like polygons and rectangles) are outlined. If the mode is 1, they are filled.

PIL.ImageDraw.Draw. setfont ( font ) ¶

Deprecated since version 1.1.5.

Sets the default font to use for the text method.

Parameters: font – An ImageFont instance.

© Copyright 1997-2011 by Secret Labs AB, 1995-2011 by Fredrik Lundh, 2010-2013 Alex Clark. Revision 0f05eb287a223ce106848cd048cfcb45e9faa565 .

Versions latest stable Downloads On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.

Источник

Рисуем геометрические фигуры в Python с помощью Pillow

Рисуем в Pillow Python

Модуль ImageDraw из библиотеки обработки изображений Pillow (PIL) предоставляет методы для рисования круга, квадрата и прямой линии в Python.

Создание объекта Draw в Python

Используя объекта Image мы создадим фоновое изображение на которой мы будем рисовать наши фигуры при помощи объекта Draw . Не забудьте импортировать модуль Image и ImageDraw в начале кода.

Здесь создается пустое изображение с размером 500 на 300 пикселей и с тёмно желтым фоном.

Создание картинки в Pillow

Рисуем фигуры в Pillow: ellipse, rectangle и line

Вызываем методы рисования из объекта Draw для рисования фигур на нашем желтом фоне.

Рисуем эллипс, прямоугольник и прямую линию в качестве примера.

Рисуем фигуры в Python

Справочник по параметрам методов рисования

Даже если, способы рисования отличаются в зависимости от используемого метода, следующие параметры являются общими для всех.

Область рисования — xy

Параметр xy указывает прямоугольную область для рисования новой фигуры.

Уточняется один из следующих форматов:

  • (((Верхняя левая x координата, Верхняя левая y координата), (нижняя правая x координата, нижняя правая y координата)) ;
  • (Верхняя левая x координата, Верхняя левая y координата, нижняя правая x координата, нижняя правая y координата) .

В методах line() , polygon() и point() используются многочисленные координаты вместо двух точек, представляющих прямоугольную область.

Метод line() рисует прямую линию, которая связывает каждую точку, polygon() рисует многоугольник, а метод point() рисует точку в 1 пиксель для каждой указанной точки.

Параметр fill — заполняем фигуру определенным цветом

Параметр fill указывает какой цвет будет использован для заполнения нашей геометрической формы.

Спецификация формата цвета отличается в зависимости от указанного режима изображения (объект Image ):

  • RGB : Указывает значение цвета в форме (R, G, B) ;
  • L (Черно-белое): Указывает значение (0-255) как целое число).

Значение по умолчанию None (не заполнено).

Есть три способа указать цвет, возьмем красный цвет, его можно записать так:

  • текстовый формат: red;
  • CSS формат (Шестнадцатеричный): #FF0000
  • RGB: (255, 0, 0)

Стоит учесть тот факт, что текстовый формат не имеет все цвета, кол-во доступных цветов ограничено в коде самой библиотеки. Вот весь список: https://github.com/python-pillow/Pillow/blob/8.1.0/src/PIL/ImageColor.py#L148

Лучше всего использовать шестнадцатеричный формат #FFFFFF (белый).

Параметр outline — цвет границ

Параметр outline указывает на цвет границы фигуры.

Спецификация формата цвета такая же, как и у параметра fill которого мы обсуждали выше. Значение по умолчанию равно None (без границ).

Параметр width — размер границ

Вне зависимости от рисуемой фигуры, вы можете указать размер в пикселях для границы фигуры.

Рисование эллипса и прямоугольника в Python

Метод ellipse() рисует эллипс, область рисования указывается в параметр xy . Если мы зададим четыре координата которые будут соответствовать квадрату, то у нас получится ровный круг.

Нарисуем небольшой смайл используя круги.

Источник

Fix PIL.ImageDraw.Draw.line with wide lines

I’m looking for a fix for this issue. A good solution for me would be to have the line drawn by PIL.ImageDraw have rounded ends ( capstyle in TKinter ). Is there an equivalent in PIL.ImageDraw ?

enter image description here

This is what I would like to obtain:

from PIL import Image, ImageDraw WHITE = (255, 255, 255) BLUE = "#0000ff" MyImage = Image.new('RGB', (600, 400), WHITE) MyDraw = ImageDraw.Draw(MyImage) MyDraw.line([100,100,150,200], width=40, fill=BLUE) MyDraw.line([150,200,300,100], width=40, fill=BLUE) MyDraw.line([300,100,500,300], width=40, fill=BLUE) MyImage.show() 

enter image description here

2 Answers 2

There are standard option joint=’curve’ of the ImageDraw.line designed to fix it.

Your example may look like

from PIL import Image, ImageDraw WHITE = (255, 255, 255) BLUE = "#0000ff" MyImage = Image.new('RGB', (600, 400), WHITE) MyDraw = ImageDraw.Draw(MyImage) line_points = [(100, 100), (150, 200), (300, 100), (500, 300)] MyDraw.line(line_points, width=40, fill=BLUE, joint='curve') MyImage.show() 

Special care is required to address the end-points, but joints are fixed.

Fixed line with joint='curve'

Make sure your coordinates are formatted exactly as above [(x,y). ]. line is kind of flexible with other formats (unrolled list, numpy, etc.), but these will cause headaches with «joint».

Hmm, doesn’t work for me, whatever I do. Throws TypeError: line() got an unexpected keyword argument ‘joint’ 🙁

Note: If you are drawing a polygon (out of lines), the point where the last line joins the first will not get this curve treatment. Extend the polygon so it draws all the way around and then retraces the last line, to get it looking nice.

I have the same problem as you. However, you can easily solve the problem by simply plotting a circle of the same diameter as the line widths at each vertex. Below is your code, slightly modified, to fix the problem

from PIL import Image, ImageDraw WHITE = (255, 255, 255) BLUE = "#0000ff" RED = "#ff0000" MyImage = Image.new('RGB', (600, 400), WHITE) MyDraw = ImageDraw.Draw(MyImage) # Note: Odd line widths work better for this algorithm, # even though the effect might not be noticeable at larger line widths LineWidth = 41 MyDraw.line([100,100,150,200], width=LineWidth, fill=BLUE) MyDraw.line([150,200,300,100], width=LineWidth, fill=BLUE) MyDraw.line([300,100,500,300], width=LineWidth, fill=BLUE) Offset = (LineWidth-1)/2 # I have plotted the connecting circles in red, to show them better # Even though they look smaller than they should be, they are not. # Look at the diameter of the circle and the diameter of the lines - # they are the same! MyDraw.ellipse ((150-Offset,200-Offset,150+Offset,200+Offset), fill=RED) MyDraw.ellipse ((300-Offset,100-Offset,300+Offset,100+Offset), fill=RED) MyImage.show() 

Источник

Оцените статью