Код: Выделить всё
def rotate_if_needed(image, contour):
# Get the minimum area bounding box for the contour
rect = cv2.minAreaRect(contour)
box = cv2.boxPoints(rect)
box = np.int0(box)
# Calculate the angle of rotation
angle = rect[-1]
# Adjust the angle to ensure the document is straight
if angle < -45:
angle += 90
# Expand the canvas size to prevent cutting off during rotation
(h, w) = image.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
# Calculate the new bounding dimensions after rotation
cos = np.abs(M[0, 0])
sin = np.abs(M[0, 1])
new_w = int((h * sin) + (w * cos))
new_h = int((h * cos) + (w * sin))
# Adjust the rotation matrix to take into account translation
M[0, 2] += (new_w / 2) - center[0]
M[1, 2] += (new_h / 2) - center[1]
# Perform the rotation
rotated = cv2.warpAffine(image, M, (new_w, new_h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
return rotated
Подробнее здесь: https://stackoverflow.com/questions/790 ... t-with-ocr