# How do I detect and rotate a square?

I have recently written code for detecting path colors in a 2D grid and printing the corresponding path costs and it works fine for me. Here's my code; I am currently new to OpenCV and know only C++ (no python).

The image that I had for the project was: Now I may get an image like this for the same task: I need an algorithm to detect the square in the middle of the arena, rotate it to the angle by which it becomes like the image above, and then crop the rest of the image off.

I am currently at a fix about doing this.

• What have you tried and where did you get stuck? I assume this occurs in the context of some course; have you tried the methods presented in class? What specific issues have you been facing? (Note that programming is offtopic here.) – Raphael Jun 29 '15 at 20:37
• I tried to find the first white point from the top left, then spread the points around like a concentric squares and find the first point at which there is a white dot. I manage to find coordinates of the nearest point with a white dot and applying trigonometry on the two points, I got the angle by which the image is aligned to horizontal axis. Now I don't know how to tilt the second image by the same angle to form an image like the top one. No its not part of a course, I'm learning through tutorials. Thanks in Advance. – Siddharth Jha Jun 30 '15 at 8:35

## 1 Answer

Since you asked for algorithms, I suggest you look at the Hough transform and other techniques for finding lines in an image. I suspect this will help you determine where the lines are, where the intersections are, and how much to rotate to recover the original image.

• If I get to know the angle, how do I detect the rotated square in the middle, rotate it by the angle I found and place it into a new Mat? – Siddharth Jha Jun 30 '15 at 8:21