JavaCV ~ OpenCV
It is necessary to determine the direction of a person's movement (left or right) in real time. I use JavaCV. My code gives the correct answer only based on movement in ideal conditions (there are no shadows, the lighting does not change, the person does not change the trajectory of movement):
We place the found moving object in a green rectangle, calculate the sum of the centers of mass of all rectangles, calculate the difference between the centers of mass of the previous and current frames, keep statistics from a few comparisons (to reduce the probability of an error in the final result) and on its basis we make a verdict - moves to the right or to the left.
I found the function calcGlobalOrientation(), but I don't have an example of how to use it.
Perhaps someone will give advice on how to use JavaCV with a fairly high performance and low probability of error to determine the direction of movement of the object?
if (cnts.size() > 0) {
firstEntry = true;
center_current = newPoint();
for (int i = 0; i < cnts.size(); i++) {
//continue to work only with areas that satisfy the condition
if (contourArea(cnts.get(i)) < 2000) {
continue;
}
Rect r = boundingRect(cnts.get(i));
// check if the center of mass of the figure is in the "gray" area
if (
isInside(r.x() + r.width() / 2, r.y() + r.height() / 2, getArrayGrayZone().get(0)) ||
isInside(r.x() + r.width() / 2, r.y() + r.height() / 2, getArrayGrayZone().get(1))
) {
// System.out.println("Movement in the \"grey\" zone");
continue;
}
//4th parameter - characterization of the contour of the figure ("< 0" the figure is filled, "> 0" the line thickness)
rectangle(frame, r, new Scalar(0, 255, 0, 0), 3, 0, 0);
if (firstEntry) {
//+1 frame with recognized motion that satisfies the condition
counterFrame++;
firstEntry = false;
}
//look for the center of mass of the given rectangle
center = newPoint();
center.x = r.x() + r.width() / 2;
center.y = r.y() + r.height() / 2;
//if the current center of mass has not yet been calculated, then enter a new value
if (center_current.x == 0) {
center_current = center;
continue;
}
//calculate the common center of mass of the current and past rectangles
center_current.x = (center_current.x + center.x) / 2;
center_current.y = (center_current.y + center.y) / 2;
}
//if it was possible to calculate the current center of mass of the rectangles
if (center_current.x != 0) {
//if the previous center of mass has not yet been calculated, then equalize the current and previous
if (center_prev.x == 0) {
center_prev = center_current;
} else {
difference = new Vec2d(center_current.x - center_prev.x, center_current.y - center_prev.y);
if (difference.x < 0) {
indexL++;
}
if (difference.x > 0) {
indexR++;
}
}
}
}
if (counterFrame % 10 == 0 && counterFrame > 0) {
if (indexR > indexL) {
System.out.println(
"Right" + df.format(new Date()));
}
if (indexL > indexR) {
System.out.println(
"Left" + df.format(new Date()));
}
//reset the counter of frames with a recognized motion that satisfies the condition
counterFrame = 0;
//reset the "statistical" variables for detecting shift to the right or left
indexL = indexR = 0;
}
//make current center of mass "previous"
center_prev = center_current;
Related
I am still new to OpenCV, i am trying to detect object of multiple colour as well as center of the object. The color i need to detect is Red, Blue and Yellow. My program able to detect different colour, but it can't detect centroid of the same colour. The object with the bigger pixel will take the priority. Is there anythings i miss or where can i improve in my code?
main.cpp
inRange(imgHSV, Scalar(redLowH,redLowS,redLowV), Scalar(redHighH, redHighS, redHighV), imgThresred); //Threshold the image
inRange(imgHSV, Scalar(blueLowH,blueLowS,blueLowV), Scalar(blueHighH, blueHighS, blueHighV), imgThresblue); //Threshold the image
inRange(imgHSV, Scalar(yellowLowH,yellowLowS,yellowLowV), Scalar(yellowHighH, yellowHighS, yellowHighV), imgThresyellow); //Threshold the image
Moments rMoments = moments(imgThresred);
double dM01_r = rMoments.m01;
double dM10_r = rMoments.m10;
double dArea_r = rMoments.m00;
//Calculate area of Red Object
if (dArea_r > 10000)
{
//calculate the position of the ball
posX_r = dM10_r / dArea_r;
posY_r = dM01_r / dArea_r;
//cout<<"The red object : X coodinate is "<< posX_r <<", Y coodinate is "<< posY_r <<endl;
if (iLastX_r >= 0 && iLastY_r >= 0 && posX_r >= 0 && posY_r >= 0)
{
//Draw a red line from the previous point to the current point
line(imgLines_r, Point(posX_r, posY_r), Point(iLastX_r, iLastY_r), Scalar(0,0,255), 10);
}
iLastX_r = posX_r;
iLastY_r = posY_r;
}
imgOriginal = imgOriginal + imgLines_r + imgLines_b + imgLines_y;
//Check Object region in the image
if (posX_r < 100)
{
cout<<"left side"<<endl;
}else
{
cout<<"no"<<endl;
}
I am fairly new to iOS development. I have just started about a month or two ago. I have an idea for an application, but it would require Gesture Recognizers. I have looked for the documentation for Gesture Recognizers but as far as I can tell, it can only detect 4 directions. Up, left, right, and down. Is there anyway to write some code that will let you detect any direction the user swipes. For example, if the user were to swipe towards the upper-right direction or bottom-right direction, is there a way to detect that?
EDIT: After thinking about this I have come up with a better way to explain what I need code for. If I was developing a game for iOS and the user is usually in a camera view (birds-eye view) and I wanted to allow them to move their view in a map so that they could perhaps view an enemy's base or their ally's base, how would I detect those diagonal swipes rather than just up, right, left, and down swipes?
I think you are a little confused.
UISwipeGestureRecognizer is a subclass of UIGestureRecognizer, and, as you say, it only detects swipes for those 4 directions.
But then there's UIPanGestureRecognizer which you can use to detect movement in any direction. It gives you a method called translationInView: which gives you just that, the change of the position of your finger in whichever direction.
I ran across your question, since it was something similar to what I wanted to do, but then ended up not using it. So I figured I'd leave the code here for posterity. Just use an UIPanGestureRecognizer and set a method similar to this one for your target/selector:
typedef enum {
NONE = 0,
LEFT = 1,
RIGHT = 2,
UP = 4,
DOWN = 8
} BLDirection;
-(void)detectDirection:(UIPanGestureRecognizer*)pan {
if (pan.state == UIGestureRecognizerStateEnded) {
CGPoint stopPan = [pan translationInView:self.view];
CGPoint velocity = [pan velocityInView:self.view];
int direction = NONE;
// first determine the directions
if (velocity.x < 0) {
direction |= LEFT;
} else if (velocity.x > 0) {
direction |= RIGHT;
}
if (velocity.y < 0) {
direction |= UP;
} else if (velocity.y > 0) {
direction |= DOWN;
}
// now we figure out the angle of the swipe
double x2 = stopPan.x;
double x1 = 0;
double y2 = abs(stopPan.y);
double y1 = 0;
// angle is in degrees
double angle = atan((y2 - y1 + 1) / (x2 - x1 + 1)) * 57.29577951308233; // 180/pi
// mask out the vertical directions if they aren't sufficiently strong
if ((angle < 0 && angle < -55) || (angle > 0 && angle > 55)) {
direction &= (UP | DOWN);
}
// mask out the horizontal directions if they aren't sufficiently strong
if ((angle < 0 && angle > -35) || (angle > 0 && angle < 35)) {
direction &= (LEFT | RIGHT);
}
NSLog(#"Direction is %s%s%s%s", ((direction & UP) == UP) ? "UP" : "",
((direction & DOWN) == DOWN) ? "DOWN" : "",
((direction & LEFT) == LEFT) ? "LEFT" : "",
((direction & RIGHT) == RIGHT) ? "RIGHT" : "");
// do something here now that you know the direction. The direction could be one of the following:
// UP
// DOWN
// LEFT
// RIGHT
// UP|LEFT
// UP|RIGHT
// DOWN|LEFT
// DOWN|RIGHT
}
}
As my tile says that I want to get random number for origin (X-Axis & y-Axis) so in my whole screen in iPad landscape I have 1 rectangle, I want to get random number for origin which out of this rectangle, so obiously I want to get random number for X-Axis between max and min and same as for Y-Axis.
I tried with following answers but not helpful for me.
Generate Random Numbers Between Two Numbers in Objective-C
Generate a random float between 0 and 1
Generate random number in range in iOS?
For more clear see below image
In above image I just want to find random number (for origin) of GREEN screen. How can I achieve it ?
Edited
I had tried.
int randNum = rand() % ([max intValue] - [min intValue]) + [min intValue];
Same for both X-Axis & y-Axis.
If the blue exclusion rectangle is not "too large" compared to the green screen rectangle
then the easiest solution is to
create a random point inside the green rectangle,
check if the point lies inside the blue rectangle, and
repeat the process if necessary.
That would look like:
CGRect greenRect = ...;
CGRect blueRect = ...;
CGPoint p;
do {
p = CGPointMake(greenRect.origin.x + arc4random_uniform(greenRect.size.width),
greenRect.origin.y + arc4random_uniform(greenRect.size.height));
} while (CGRectContainsPoint(blueRect, p));
If I remember correctly, the expected number of iterations is G/(G - B), where G is
the area of the green rectangle and B is the area of the blue rectangle.
What if you first determined x within the green rectangle like this:
int randomX = arc4random()%greenRectangle.frame.size.width;
int randomY; // we'll do y later
Then check if this is inside the blue rectangle:
if(randomX < blueRectangle.frame.origin.x && randomX > (blueRectangle.frame.origin.x + blueRectangle.frame.size.width))
{
//in this case we are outside the rectangle with the x component
//so can randomly generate any y like this:
randomY = arc4random()%greenRectangle.frame.size.height;
}
//And if randomX is in the blue rectangle then we can use the space either before or after it:
else
{
//randomly decide if you are going to use the range to the left of blue rectangle or to the right
BOOL shouldPickTopRange = arc4random()%1;
if(shouldPickTopRange)
{
//in this case y can be any point before the start of blue rectangle
randomY = arc4random()%blueRectangle.frame.origin.y;
}
else
{
//in this case y can be any point after the blue rectangle
int minY = blueRectangle.frame.origin.y + blueRectangle.frame.size.height;
int maxY = greenRectangle.frame.size.height;
randomY = arc4random()%(maxY - minY + 1) + minY;
}
}
Then your random point would be:
CGPoint randomPoint = CGPointMake(randomX, randomY);
The only thing missing above is to check if your blue rectangle sits at y = 0 or at the very bottom of green rectangle.
[Apologies I did this with OS X, translation is straightforward]
A non-iterative solution:
- (NSPoint) randomPointIn:(NSRect)greenRect excluding:(NSRect)blueRect
{
// random point on green x-axis
int x = arc4random_uniform(NSWidth(greenRect)) + NSMinX(greenRect);
if (x < NSMinX(blueRect) || x > NSMaxX(blueRect))
{
// to the left or right of the blue, full height available
int y = arc4random_uniform(NSHeight(greenRect)) + NSMinY(greenRect);
return NSMakePoint(x, y);
}
else
{
// within the x-range of the blue, avoid it
int y = arc4random_uniform(NSHeight(greenRect) - NSHeight(blueRect)) + NSMinY(greenRect);
if (y >= NSMinY(blueRect))
{
// not below the blue, step over it
y += NSHeight(blueRect);
}
return NSMakePoint(x, y);
}
}
This picks a random x-coord in the range of green. If that point is outside the range of blue it picks a random y-coord in the range of green; otherwise it reduces the y range by the height of blue, produces a random point, and then increases it if required to avoid blue.
There are other solutions based on picking a uniform random point in the available area (green - blue) and then adjusting, but the complexity isn't worth it I think (I haven't done the stats).
Addendum
OK folk seem concerned over uniformity, so here is the algorithm mentioned in my last paragraph. We're picking an "point" with integer coords so the number of points to pick from is the green area minus the blue area. Pick a point randomly in this range. Now place it into one of the rectangles below, left, right or above the blue:
// convenience
int RectArea(NSRect r) { return (int)NSWidth(r) * (int)NSHeight(r); }
- (NSPoint) randomPointIn:(NSRect)greenRect excluding:(NSRect)blueRect
{
// not we are using "points" with integer coords so the
// bottom left point is 0,0 and the top right (width-1, height-1)
// you can adjust this to suit
// the number of points to pick from is the diff of the areas
int availableArea = RectArea(greenRect) - RectArea(blueRect);
int pointNumber = arc4random_uniform(availableArea);
// now "just" locate pointNumber into the available space
// we consider four rectangles, one each full width above and below the blue
// and one each to the left and right of the blue
int belowArea = NSWidth(greenRect) * (NSMinY(blueRect) - NSMinY(greenRect));
if (pointNumber < belowArea)
{
return NSMakePoint(pointNumber % (int)NSWidth(greenRect) + NSMinX(greenRect),
pointNumber / (int)NSWidth(greenRect) + NSMinY(greenRect));
}
// not below - consider to left
pointNumber -= belowArea;
int leftWidth = NSMinX(blueRect) - NSMinX(greenRect);
int leftArea = NSHeight(blueRect) * leftWidth;
if (pointNumber < leftArea)
{
return NSMakePoint(pointNumber % leftWidth + NSMinX(greenRect),
pointNumber / leftWidth + NSMinY(blueRect));
}
// not left - consider to right
pointNumber -= leftArea;
int rightWidth = NSMaxX(greenRect) - NSMaxX(blueRect);
int rightArea = NSHeight(blueRect) * rightWidth;
if (pointNumber < rightArea)
{
return NSMakePoint(pointNumber % rightWidth + NSMaxX(blueRect),
pointNumber / rightWidth + NSMinY(blueRect));
}
// it must be above
pointNumber -= rightArea;
return NSMakePoint(pointNumber % (int)NSWidth(greenRect) + NSMinX(greenRect),
pointNumber / (int)NSWidth(greenRect) + NSMaxY(blueRect));
}
This is uniform, but whether it is worth it you'll have to decide.
Okay. This was bothering me, so I did the work. It's a lot of source code, but computationally lightweight and probabilistically correct (haven't tested).
With all due respect to #MartinR, I think this is superior insofar as it doesn't loop (consider the case where the contained rect covers a very large portion of the outer rect). And with all due respect to #CRD, it's a pain, but not impossible to get the desired probabilities. Here goes:
// Find a random position in rect, excluding a contained rect called exclude
//
// It looks terrible, but it's just a lot of bookkeeping.
// Divide rect into 8 regions, like a tic-tac-toe board, excluding the center square
// Reading left to right, top to bottom, call these: A,B,C,D, (no E, it's the center) F,G,H,I
// The random point must be in one of these regions, choose by throwing a random dart, using
// cumulative probabilities to choose. The likelihood that the dart will be in regions A-I is
// the ratio of each's area to the total (less the center)
// With a target rect, correctly selected, we can easily pick a random point within it.
+ (CGPoint)pointInRect:(CGRect)rect excluding:(CGRect)exclude {
// find important points in the grid
CGFloat xLeft = CGRectGetMinX(rect);
CGFloat xCenter = CGRectGetMinX(exclude);
CGFloat xRight = CGRectGetMaxX(exclude);
CGFloat widthLeft = exclude.origin.x-CGRectGetMinX(rect);
CGFloat widthCenter = exclude.size.width;
CGFloat widthRight = CGRectGetMaxY(rect)-CGRectGetMaxX(exclude);
CGFloat yTop = CGRectGetMinY(rect);
CGFloat yCenter = exclude.origin.y;
CGFloat yBottom = CGRectGetMaxY(exclude);
CGFloat heightTop = exclude.origin.y-CGRectGetMinY(rect);
CGFloat heightCenter = exclude.size.height;
CGFloat heightBottom = CGRectGetMaxY(rect)-CGRectGetMaxY(exclude);
// compute the eight regions
CGFloat areaA = widthLeft * heightTop;
CGFloat areaB = widthCenter * heightTop;
CGFloat areaC = widthRight * heightTop;
CGFloat areaD = widthLeft * heightCenter;
CGFloat areaF = widthRight * heightCenter;
CGFloat areaG = widthLeft * heightBottom;
CGFloat areaH = widthCenter * heightBottom;
CGFloat areaI = widthRight * heightBottom;
CGFloat areaSum = areaA+areaB+areaC+areaD+areaF+areaG+areaH+areaI;
// compute the normalized probabilities
CGFloat pA = areaA/areaSum;
CGFloat pB = areaB/areaSum;
CGFloat pC = areaC/areaSum;
CGFloat pD = areaD/areaSum;
CGFloat pF = areaF/areaSum;
CGFloat pG = areaG/areaSum;
CGFloat pH = areaH/areaSum;
// compute cumulative probabilities
CGFloat cumB = pA+pB;
CGFloat cumC = cumB+pC;
CGFloat cumD = cumC+pD;
CGFloat cumF = cumD+pF;
CGFloat cumG = cumF+pG;
CGFloat cumH = cumG+pH;
// now pick which region we're in, using cumulatvie probabilities
// whew, maybe we should just use MartinR's loop. No No, we've come too far!
CGFloat dart = uniformRandomUpTo(1.0);
CGRect targetRect;
// top row
if (dart < pA) {
targetRect = CGRectMake(xLeft, yTop, widthLeft, heightTop);
} else if (dart >= pA && dart < cumB) {
targetRect = CGRectMake(xCenter, yTop, widthCenter, heightTop);
} else if (dart >= cumB && dart < cumC) {
targetRect = CGRectMake(xRight, yTop, widthRight, heightTop);
}
// middle row
else if (dart >= cumC && dart < cumD) {
targetRect = CGRectMake(xRight, yCenter, widthRight, heightCenter);
} else if (dart >= cumD && dart < cumF) {
targetRect = CGRectMake(xLeft, yCenter, widthLeft, heightCenter);
}
// bottom row
else if (dart >= cumF && dart < cumG) {
targetRect = CGRectMake(xLeft, yBottom, widthLeft, heightBottom);
} else if (dart >= cumG && dart < cumH) {
targetRect = CGRectMake(xCenter, yBottom, widthCenter, heightBottom);
} else {
targetRect = CGRectMake(xRight, yBottom, widthRight, heightBottom);
}
// yay. pick a point in the target rect
CGFloat x = uniformRandomUpTo(targetRect.size.width) + CGRectGetMinX(targetRect);
CGFloat y = uniformRandomUpTo(targetRect.size.height)+ CGRectGetMinY(targetRect);
return CGPointMake(x, y);
}
float uniformRandomUpTo(float max) {
return max * arc4random_uniform(RAND_MAX) / RAND_MAX;
}
Try this code, Worked for me.
-(CGPoint)randomPointInRect:(CGRect)r
{
CGPoint p = r.origin;
p.x += arc4random_uniform((u_int32_t) CGRectGetWidth(r));
p.y += arc4random_uniform((u_int32_t) CGRectGetHeight(r));
return p;
}
I don't like piling onto answers. However, the provided solutions do not work, so I feel obliged to chime in.
Martin's is fine, and simple... which may be all you need. It does have one major problem though... finding the answer when the inner rectangle dominates the containing rectangle could take quite a long time. If it fits your domain, then always choose the simplest solution that works.
jancakes solution is not uniform, and contains a fair amount of bias.
The second solution provided by dang just plain does not work... because arc4_random takes and returns uint32_t and not a floating point value. Thus, all generated numbers should fall into the first box.
You can address that by using drand48(), but it's not a great number generator, and has bias of its own. Furthermore, if you look at the distribution generated by that method, it has heavy bias that favors the box just to the left of the "inner box."
You can easily test the generation... toss a couple of UIViews in a controller, add a button handler that plots 100000 "random" points and you can see the bias clearly.
So, I hacked up something that is not elegant, but does provide a uniform distribution of random numbers in the larger rectangle that are not in the contained rectangle.
You can surely optimize the code and make it a bit easier to read...
Caveat: Will not work if you have more than 4,294,967,296 total points. There are multiple solutions to this, but this should get you moving in the right direction.
- (CGPoint)randomPointInRect:(CGRect)rect
excludingRect:(CGRect)excludeRect
{
excludeRect = CGRectIntersection(rect, excludeRect);
if (CGRectEqualToRect(excludeRect, CGRectNull)) {
return CGPointZero;
}
CGPoint result;
uint32_t rectWidth = rect.size.width;
uint32_t rectHeight = rect.size.height;
uint32_t rectTotal = rectHeight * rectWidth;
uint32_t excludeWidth = excludeRect.size.width;
uint32_t excludeHeight = excludeRect.size.height;
uint32_t excludeTotal = excludeHeight * excludeWidth;
if (rectTotal == 0) {
return CGPointZero;
}
if (excludeTotal == 0) {
uint32_t r = arc4random_uniform(rectHeight * rectWidth);
result.x = r % rectWidth;
result.y = r /rectWidth;
return result;
}
uint32_t numValidPoints = rectTotal - excludeTotal;
uint32_t r = arc4random_uniform(numValidPoints);
uint32_t numPointsAboveOrBelowExcludedRect =
(rectHeight * excludeWidth) - excludeTotal;
if (r < numPointsAboveOrBelowExcludedRect) {
result.x = (r % excludeWidth) + excludeRect.origin.x;
result.y = r / excludeWidth;
if (result.y >= excludeRect.origin.y) {
result.y += excludeHeight;
}
} else {
r -= numPointsAboveOrBelowExcludedRect;
uint32_t numPointsLeftOfExcludeRect =
rectHeight * excludeRect.origin.x;
if (r < numPointsLeftOfExcludeRect) {
uint32_t rowWidth = excludeRect.origin.x;
result.x = r % rowWidth;
result.y = r / rowWidth;
} else {
r -= numPointsLeftOfExcludeRect;
CGFloat startX =
excludeRect.origin.x + excludeRect.size.width;
uint32_t rowWidth = rectWidth - startX;
result.x = (r % rowWidth) + startX;
result.y = r / rowWidth;
}
}
return result;
}
I am using Kineticjs. I am trying to have bound (dragBoundFunc) on the drag like the one below (http://jsfiddle.net/m1erickson/n5xMs):
dragBoundFunc: function (pos) {
var X = pos.x;
var Y = pos.y;
if (X < minX) {
X = minX;
}
if (X > maxX) {
X = maxX;
}
if (Y < minY) {
Y = minY;
}
if (Y > maxY) {
Y = maxY;
}
return ({
x: X,
y: Y
});
}
});
and I am trying use this approach for a group which is drag-able and re-sizable like this http://jsbin.com/iyimuy/125/edit but I am not able to make it work.I would love to hear some comments.
You seem to be overthinking the problem.
For example, here’s how to enforce the right boundary (in pseudo-code).
You have moved darth beyond the right side of yoda if:
darthRight > yodaRight.
Calculate darthRight:
In dragBoundFunc, the pos variable gives you the current top-left x/y of darth.
darthRight = posX + darthWidth
Calculate yodaRight:
yodaRight = yodaX + yodaWidth
To correct for darths move outside yoda:
Pull darths left side back inside yoda until its a full darthWidth inside yodaRight.
posX = yodaRight - darthWidth
Done!
Now repeat for the other 3 boundaries...
This question was already asked, but I still don't get it. I obtain a homography matrix by calling cv::findHomography from a set of points. I need to check whether it's relevant or not.The proposed method is to calculate maximum reprojection error for inliers and compare it with a threshold. But after such filtration I keep getting insane transformations with object bounding box transforming to almost a straight line or some strange non-convex quadrangle, with self-intersections etc.What constraints can be used to check if the homography matrix itself is adequate?
Your question is mathematical. Given a matrix of 3x3 decide whether it represents a good rigid transformation.
It is hard to define what is "good" but here are some clues that can help you
Homography should preserve the direction of polygonal points. Design a simple test. points (0,0), (imwidth,0), (width,height), (0,height) represent a quadrilateral with clockwise arranged points. Apply homography on those points and see if they are still clockwise arranged if they become counter clockwise your homography is flipping (mirroring) the image which is sometimes still ok. But if your points are out of order than you have a "bad homography"
The homography doesn't change the scale of the object too much. For example if you expect it to shrink or enlarge the image by a factor of up to X, just check this rule. Transform the 4 points (0,0), (imwidth,0), (width-1,height), (0,height) with homography and calculate the area of the quadrilateral (opencv method of calculating area of polygon) if the ratio of areas is too big (or too small), you probably have an error.
Good homography is usually uses low values of perspectivity. Typically if the size of the image is ~1000x1000 pixels those values should be ~0.005-0.001. High perspectivity will cause enormous distortions which are probably an error. If you don't know where those values are located read my post:
trying to understand the Affine Transform
. It explains the affine transform math and the other 2 values are perspective parameters.
I think that if you check the above 3 condition (condition 2 is the most important) you will be able to detect most of the problems.
Good luck
Edit: This answer is irrelevant to the question, but the discussion may be helpful for someone who tries to use the matching results for recognition like I did!
This might help someone:
Point2f[] objCorners = { new Point2f(0, 0),
new Point2f(img1.Cols, 0),
new Point2f(img1.Cols, img1.Rows),
new Point2f(0, img1.Rows) };
Point2d[] sceneCorners = MyPerspectiveTransform3(objCorners, homography);
double marginH = img2.Width * 0.1d;
double marginV = img2.Height * 0.1d;
bool homographyOK = isInside(-marginH, -marginV, img2.Width + marginH, img2.Height + marginV, sceneCorners);
if (homographyOK)
for (int i = 1; i < sceneCorners.Length; i++)
if (sceneCorners[i - 1].DistanceTo(sceneCorners[i]) < 1)
{
homographyOK = false;
break;
}
if (homographyOK)
homographyOK = isConvex(sceneCorners);
if (homographyOK)
homographyOK = minAngleCheck(sceneCorners, 20d);
private static bool isInside(dynamic minX, dynamic minY, dynamic maxX, dynamic maxY, dynamic coors)
{
foreach (var c in coors)
if ((c.X < minX) || (c.Y < minY) || (c.X > maxX) || (c.Y > maxY))
return false;
return true;
}
private static bool isLeft(dynamic a, dynamic b, dynamic c)
{
return ((b.X - a.X) * (c.Y - a.Y) - (b.Y - a.Y) * (c.X - a.X)) > 0;
}
private static bool isConvex<T>(IEnumerable<T> points)
{
var lst = points.ToList();
if (lst.Count > 2)
{
bool left = isLeft(lst[0], lst[1], lst[2]);
lst.Add(lst.First());
for (int i = 3; i < lst.Count; i++)
if (isLeft(lst[i - 2], lst[i - 1], lst[i]) != left)
return false;
return true;
}
else
return false;
}
private static bool minAngleCheck<T>(IEnumerable<T> points, double angle_InDegrees)
{
//20d * Math.PI / 180d
var lst = points.ToList();
if (lst.Count > 2)
{
lst.Add(lst.First());
for (int i = 2; i < lst.Count; i++)
{
double a1 = angleInDegrees(lst[i - 2], lst[i-1]);
double a2 = angleInDegrees(lst[i], lst[i - 1]);
double d = Math.Abs(a1 - a2) % 180d;
if ((d < angle_InDegrees) || ((180d - d) < angle_InDegrees))
return false;
}
return true;
}
else
return false;
}
private static double angleInDegrees(dynamic v1, dynamic v2)
{
return (radianToDegree(Math.Atan2(v1.Y - v2.Y, v1.X - v2.X))) % 360d;
}
private static double radianToDegree(double radian)
{
var degree = radian * (180d / Math.PI);
if (degree < 0d)
degree = 360d + degree;
return degree;
}
static Point2d[] MyPerspectiveTransform3(Point2f[] yourData, Mat transformationMatrix)
{
Point2f[] ret = Cv2.PerspectiveTransform(yourData, transformationMatrix);
return ret.Select(point2fToPoint2d).ToArray();
}