-2

Let's consider we have a rotated rectangle specified by (centerx, centery, width, height, angle). The question is how to draw this rotated bounding box with a specific filled value e.g. 5 in a image with only a simple command.

What I need is something like the command below:

draw.rectangle(centerx, centery, width, height, angle, value, 'filled')

OpenCV, PIL, shapely and Matplotlib libraries do not have a simple command for this case. I searched in the net and could not find a solution for this.

One solution could be this, but it does not consider filling the rectangle.

martineau
  • 119,623
  • 25
  • 170
  • 301
Majid Azimi
  • 907
  • 1
  • 11
  • 29
  • Is [pygame](https://www.pygame.org/docs/) a option? – MegaIng May 06 '18 at 21:42
  • @MegaIng I tried pygame. It did not have a command for this. I made a function for this in the end as no libraries seem to have a off-the-shelf command for this purpose. – Majid Azimi May 06 '18 at 23:54

1 Answers1

0

After trying more I came up with the following solution which works:

import numpy as np
from PIL import Image, ImageDraw
import math
import numpy.matlib as npm

def convert5Pointto8Point(cx_, cy_, w_, h_, a_):

    theta = math.radians(a_)
    bbox = npm.repmat([[cx_], [cy_]], 1, 5) + \
       np.matmul([[math.cos(theta), math.sin(theta)],
                  [-math.sin(theta), math.cos(theta)]],
                 [[-w_ / 2, w_/ 2, w_ / 2, -w_ / 2, w_ / 2 + 8],
                  [-h_ / 2, -h_ / 2, h_ / 2, h_ / 2, 0]])
    # add first point
    x1, y1 = bbox[0][0], bbox[1][0]
    # add second point
    x2, y2 = bbox[0][1], bbox[1][1]
    # add third point
    #x3, y3 = bbox[0][4], bbox[1][4]   # نوک پیکان برای به نمایشگذاری
    # add forth point
    x3, y3 = bbox[0][2], bbox[1][2]
    # add fifth point
    x4, y4 = bbox[0][3], bbox[1][3]

    return [x1, y1, x2, y2, x3, y3, x4, y4]


img = Image.new('L', (width, height), 0)
polygon = convert5Pointto8Point(50, 100, 30, 10, -50)
ImageDraw.Draw(img).polygon(polygon, outline=value, fill=value)         
plt.imshow(img)
plt.show()
Majid Azimi
  • 907
  • 1
  • 11
  • 29