Implementation method of python opencv to rotate image without cropping picture

  • 2021-07-13 05:30:02
  • OfStack

Recently, when doing deep learning, we need to use the operation related to image processing. The picture rotation method found on Du Niang is 1000 articles and 1 law, and the rotated pictures are not the original size, which is very distressing. Therefore, google went to the website of Waiguoren to pull a method, which is easy to use, and once again dislikes the phenomenon of copying articles in the world, although I also copy Waiguoren.

No more nonsense, just stick the code.


def rotate_bound(image, angle):
  # grab the dimensions of the image and then determine the
  # center
  (h, w) = image.shape[:2]
  (cX, cY) = (w // 2, h // 2)
 
  # grab the rotation matrix (applying the negative of the
  # angle to rotate clockwise), then grab the sine and cosine
  # (i.e., the rotation components of the matrix)
  M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)
  cos = np.abs(M[0, 0])
  sin = np.abs(M[0, 1])
 
  # compute the new bounding dimensions of the image
  nW = int((h * sin) + (w * cos))
  nH = int((h * cos) + (w * sin))
 
  # adjust the rotation matrix to take into account translation
  M[0, 2] += (nW / 2) - cX
  M[1, 2] += (nH / 2) - cY
 
  # perform the actual rotation and return the image
  return cv2.warpAffine(image, M, (nW, nH))

Needless to say, the first parameter through opencv read the image, the second parameter into the need to rotate the angle, enjoy!


Related articles: