Introduction
If you have worked with Azure Cognitive Service APIs like OCR API, Read API, or Form Recognizer API, you might have come across a bounding box in the read results of the response. If the input you have given is slightly tilted, the response will also be tilted. The response also contains the angle by which the input page is tilted. To manipulate the results we sometimes need to rotate the boundingBox in the response with the tilted angle to do some operations.
Here we are looking at how this rotation can be done. Here is a Receipt from KSEB captured in an angle. We first give it to Azure Read API to get the JSON output.
Sample Input is given to Azure Read API

Sample Output from Azure Read API
{
"status": "succeeded",
"createdDateTime": "2020-12-21T15:13:55Z",
"lastUpdatedDateTime": "2020-12-21T15:13:56Z",
"analyzeResult": {
"version": "3.0.0",
"readResults": [
{
"page": 1,
"angle": 7.6307,
"width": 445,
"height": 1242,
"unit": "pixel",
"lines": [
....
....
....
{
"boundingBox": [
185,
91,
366,
113,
364,
131,
183,
109
],
"text": "Demand/Disconnection Notice",
"words": [
{
"boundingBox": [
186,
92,
319,
109,
318,
126,
184,
109
],
"text": "Demand/Disconnection",
"confidence": 0.751
},
{
"boundingBox": [
323,
109,
366,
114,
365,
131,
321,
126
],
"text": "Notice",
"confidence": 0.907
}
]
},
....
....
....
]
}
]
}
}
The above JSON response from Azure Read API says the Receipt is tilted by an angle of 7.6307 degrees. In order to do some manipulations based on the coordinates in the bounding box we need to rotate this by the angle of 7.6307.
Rotate a point p by n degrees with respect to the origin o
Suppose we need to rotate a point by n degrees with respect to the origin o we may call a custom function described below by calling it.
rotatedPoint = rotate(p, o, n);
The custom function rotates is shown below, which also needs Numpy to work.
import numpy as np
def rotate(point, origin, degrees):
radians = np.deg2rad(degrees)
x, y = point
offset_x, offset_y = origin
adjusted_x = (x - offset_x)
adjusted_y = (y - offset_y)
cos_rad = np.cos(radians)
sin_rad = np.sin(radians)
qx = offset_x + cos_rad * adjusted_x + sin_rad * adjusted_y
qy = offset_y + -sin_rad * adjusted_x + cos_rad * adjusted_y
return qx, qy
Building a function for correcting angle of coordinates bounding box in response
The bounding box contains 8 points as a list in the order.
[
"left-top-x",
"left-top-y",
"right-top-x",
"right-top-y",
"right-bottom-x",
"right-bottom-y",
"left-bottom-x",
"left-bottom-y"
]
So to rotate a bounding box we may loop through the list by incrementing by 2 on each cycle as below where:
angle = analysis["analyzeResult"]["readResults"][index]["angle"]
Here angle=7.6307 and I try to rotate the picture by origin so that is equal to (0,0)
for ind in range(0, 7, 2):
bBox[ind], bBox[ind + 1] = rotate((bBox[ind], bBox[ind + 1]), (0, 0), angle)

Join the conversation! Your thoughts help the community grow.