Reputation: 324
I have an image and I want to rotate this image, to be like this : Rotation must be automatic. in other hand angle of rotation must be calculated.
[1 - Image ]
Is there any idea for this rotation on openCV?
And how can I extract a small rectangle on this image? like this : (I have marked some region with red color)
[2 - Image]
Is there any idea for extracting this region from this image on OpenCV?
Upvotes: 2
Views: 1378
Reputation: 12624
I don't know openCV, but you added the C# and C++ tags, which make me suppose that you would accept an algorithm that can be implemented in these languages.
To answer your first question:
If your images are all similar to the ones you provided, you could do something like this (these are not necessarily sequential steps, they are numbered just for ease of reference):
convert to black & white (you could do this only conceptually, if you prefer, by comparing pixel values to a threshold, in what follows)
travel along the black outline in vertical, horizontal and diagonal single-pixel steps
remember N pairs of coordinates while you travel, so that N is below the expected minimum length, in pixels, of a straight line of your images (you will have to tune N: too long gives you too little data, too short gives you too much noise)
from the coordinates of the current point and the point N steps back, calculate m
and q
ofy = m x + q
if abs(Δx) ≤ abs(Δy)
or m'
and q'
of x = m' y + q'
otherwise, and make 4 histograms thereof, with the resolution you need
smooth a bit your histograms (e.g., by adding to each channel a bit of the value of its neighbor channels)
find the maxima of m
, m'
, q
and q'
, and, after removing a surrounding of the maxima of q
and q'
, the other 2 (local) maxima of q
and q'
; these will be your estimate of the parameters of the equations of the 4 bounding lines of your rectangle, with m ≅ -m'
(depending on your desired final result you can use m
, m'
, or, e.g. (m-m')/2
)
find the rotation or the affine transformation that puts your rectangle into the desired position (e.g., the intersection of two of the above lines may have to be transformed to a certain position), and apply it
Point 2 is done by finding, at each step, the first black pixel among the 8 possible in a circular exploration around the current pixel that ends with the pixel of the previous step. E.g., if your last step was in NE (north-east) direction, and you are travelling clockwise around the contour, you explore the surroundings in this order: NW, N, NE, E, SE, S, SW (W is missing because it would have been selected by the previous step, if it had been black). You can find the starting pixel by a line scan (which will make you arrive in E direction, or W direction in case of a reverse line scan).
You should also calculate the length (in steps) of the contour. If it is much shorter than what you expect, you should discard it and make another attempt, until you find the "real" contour.
Upvotes: 2