Properties of Square in Binary image

I have the task to find the center, the side length and the rotation angle of a square in a binary image. In addition i have the following information given: Given a binary image with white (=True) background containing a single black (=False) rotated square, return the center of mass (x, y) of said square, its edge length (l) and its rotation angle (alpha). The square will always be fully contained inside the image, i.e. none of its edges intersects with the image border.Return the angle alpha in degrees, where 0° is upright and equivalent to ..., -180°, -90°, 90°, 180°, ...and the positive direction of rotation is counter-clockwise. Please note the shape of img is (height, width) with y-axis first (row-major order). This task should be solvable with only standard numpy functions.

Im not really familiar with numpy but I think I was able to get the center of the square in x and y coordinates and side length with following code:

import numpy
def find_rect(img):
    x, y, l, alpha = 0, 0, 0, 0
    black_pixels = np.argwhere(img==0)
    y, x = np.mean(black_pixels, axis=0)
    l = np.sqrt((img==0).sum()) 
    y_max1 = black_pixels[black_pixels[:,1]>= x, 0].max()
    y_max2 = black_pixels[black_pixels[:,1]<= x, 0].max()
    y_max = max(y_max1, y_max2)
    x_max = black_pixels[black_pixels[:, 0] == y_max, 1][0]
    alpha = np.degrees(np.arctan(((y_max - y)/(x_max - x))))
    return x, y, l, alpha


#the code which generates the square
from scipy.ndimage import rotate
def generate_rot_square(w, h, x, y, l, alpha):
    rect = np.ones((l, l))
    rect = rotate(rect, alpha)
    r_h, r_w = rect.shape
    r_h_1 = r_h // 2
    r_h_2 = r_h - r_h_1
    r_w_1 = r_w // 2
    r_w_2 = r_w - r_w_1

    result = np.zeros((h, w), dtype=bool)
    result[y - r_h_1:y + r_h_2, x - r_w_1:x + r_w_2] = rect > 0.9
    return 1 - result

But as soon as the square is rotated the code to get the side length if the square won't work anymore. Also I dont really have an idea on how to get the rotation angle of the square. Maybe someone can give me tips on how to solve this task.



Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation