0

I am trying to find out the angle of rotation of an object using opencv python. For this purpose I have detected the target then I am able to find out the rotation vector and I am converting it to rotation matrix and from this matrix I am calculating the euler angle. But when I rotate the object in the video then all three angles (x, y, z) changes as well as when I move the the target in the plane even though it shows variation in angles. Kindly suggest me some way to get accurate result.

This is the image of target: This is the  image of target.

  while True:
    ret, img = cap.read()

    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    ret, corners=cv2.findCirclesGrid(gray,(5,5),None)

    if ret== True:

        corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)

        # Find the rotation and translation vectors.
        _,_, rvecs, tvecs= cv2.solvePnPRansac(objp, corners2, mtx, dist)


        dst,_ = cv2.Rodrigues(rvecs)
        r = dst


        x = math.atan2(r[2][1],r[2][2])
        y = math.atan2(-r[2][0],math.sqrt((r[0][0])*r[0][0])+(r[1][0]*r[1][0]))
        z=  math.atan2(r[1][0],r[0][0])




        print("x = ",math.degrees(x))
        print("y = "math.degrees(y))
        print("z = "math.degrees(z))

Desired Output: x = 5, y = 0, z = 0
Current Output: x = 6.1 , y = 4.7, z = -2.0

Jeru Luke
  • 13,413
  • 9
  • 57
  • 71

1 Answers1

0

I am not exactly sure if this is what you want, but if you want to rotate the image based on the rotation angle of the object then:

image = cv2.imread('image.jpg',cv2.IMREAD_UNCHANGED)

gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)

ret, corners=cv2.findCirclesGrid(gray,(5,5),None)

criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.001)
corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)

((x,y),(w,h),angle) = cv2.minAreaRect(corners2)
rows,cols = image.shape[:2]
angle += 90

M = cv2.getRotationMatrix2D((int(cols/2),int(rows/2)), angle, 1.0)
nimg = cv2.warpAffine(image,M,(cols,rows))

result

zindarod
  • 5,532
  • 2
  • 23
  • 50
  • Spot on! Guess this is what the OP wanted +1. Why did you use `angle += 90`? – Jeru Luke Jul 08 '18 at 19:31
  • 1
    @JeruLuke [This post](https://stackoverflow.com/a/16042780/2286337) explains it much better than I ever could. – zindarod Jul 08 '18 at 19:34
  • @zindarod No this is not what I wanted. There are two images in which target is rotated to some degrees in x,y and z with respect to target in first image. So what I want is to get the angle of rotation of TARGET in second image with respect to first image. And I want to find the rotation angle in all three axes X , Y, and Z. – Farzam Alam Jul 10 '18 at 06:43