python - How to calc the correct angle in OpenCV and rotate image based on coordinates? - Stack Overflow

admin2025-04-29  1

I'm working on a project and I'm detecting every table in an image via OpenCV. I was able to detect, extract and crop the tables, so I already have the cropped images with all the tables.

Now my question is whether I'm able to calc the angle for every image (== table) and perform a correct rotation. The reason is that many of them are vertical or completely crooked. But I need them horizontal in order to perform OCR.

Is there a way to calc the correct angle and do the correct rotation? Does anyone has an idea or solution?

In my case:

  • I got tables which are horizontal and have an angle of < 1 (good)
  • I also have tables which are vertical but also have an angle of < 1 (not good)
  • I have vertical tables which have an angle of almost 90 but the rotation goes to the wrong direction
  • I have horizontal tables which have an angle of 90 and the code rotates the image

I checked this code (source: How to use the output of cv2.HoughLinesP() to rotate the original image?) but it produces the values I mentioned above:

import cv2
import numpy as np

# Load image, grayscale, Otsu's threshold 
image = cv2.imread('1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = 255 - gray
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# Compute rotated bounding box
coords = np.column_stack(np.where(thresh > 0))
angle = cv2.minAreaRect(coords)[-1]

if angle < -45:
    angle = -(90 + angle)
else:
    angle = -angle
print(angle)

# Rotate image to deskew
(h, w) = image.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)

cv2.imshow('thresh', thresh)
cv2.imshow('rotated', rotated)
cv2.waitKey()
转载请注明原文地址:http://anycun.com/QandA/1745940780a91417.html