# extract [0 … 2PI] rotation from 3x3 homogeneous 2D transformation matrix

I'm trying to extract the angle [0 ... 2PI] from a 3x3 homogeneous 2D transformation matrix. In fact I've found 2 very helpful posts at stackoverflow and stackexchange.

    | a  b  tx |
A = | c  d  ty |
| 0  0  1  |

angle = atan(c/d)


The thing is that I would like the angle to be in the range [0 ... 2PI]. This means that the angle needs to be adjusted somewhat. I've discovered a pattern that seems to be working and I wonder if it makes any sense or if there is a more clever way to do this.

if scale x is flipped (or scale y, seems not to matter) and (-PI/2 < angle < PI/2)
angle = angle + PI
elseif angle < 0
angle = angle + 2PI
elseif angle > 0
angle = angle // no change

-

It is known that the standard matrix is of the form $$A=\begin{bmatrix}R&c\\0^T&1\end{bmatrix}$$ where $R$ is the $2\times2$ rotation matrix $$R=\begin{bmatrix}\cos\theta&-\sin\theta\\\sin\theta&\cos\theta\end{bmatrix}$$ and $c=(R+I)d$ with $d$ being the origin of the rotation.
Thus, you must have $\sin\theta=c$ and $\cos\theta=d$, which gives $\tan\theta=\frac{c}{d}$. This can be solved using the atan2 function which is implemented in many programming languages and software packages. This function is defined as $\newcommand{\atan}[2]{\arctan\left(\frac{#1}{#2}\right)}\DeclareMathOperator{\atant}{atan2}$ $$\atant(x,y)=\begin{cases} \atan{y}{x}&x>0,y\geq0\\ \atan{y}{x}+\pi&x<0\\ \atan{y}{x}+2\pi&x>0,y<0\\ \frac{\pi}{2}&y>0,x=0\\ \frac{3\pi}{2}&y<0,x=0\\ \text{undefined}&x=0,y=0 \end{cases}.$$ This definition relies on $\arctan{x}$ lying in the domain $\left(\dfrac{-\pi}{2},\dfrac{\pi}{2}\right)$, which is the standard domain. The $\atant{x}$ function as defined above returns a result in the domain $(0,2\pi)$.