Search code examples
pythonimageopencvimage-processinghough-transform

Detect angle and rotate image using HoughLine Transform


I'm trying to rotate an image that is clearly seen with rotation.

I'm using HoughLine with opencv.

Here is the image with code below (working in google colab):

enter image description here

import numpy as np
import cv2
from scipy import ndimage
from google.colab.patches import cv2_imshow

image1 = cv2.imread('/content/rotate.png')
gray=cv2.cvtColor(image1,cv2.COLOR_BGR2GRAY)

edges = cv2.Canny(gray,50,150,apertureSize = 3)

canimg = cv2.Canny(gray, 50, 200)
lines= cv2.HoughLines(canimg, 1, np.pi/180.0, 250, np.array([]))
#lines= cv2.HoughLines(edges, 1, np.pi/180, 80, np.array([]))
for line in lines:
    rho, theta = line[0]
    a = np.cos(theta)
    b = np.sin(theta)
    x0 = a*rho
    y0 = b*rho
    x1 = int(x0 + 1000*(-b))
    y1 = int(y0 + 1000*(a))
    x2 = int(x0 - 1000*(-b))
    y2 = int(y0 - 1000*(a))

    cv2.line(image1,(x1,y1),(x2,y2),(0,0,255),2)
print(theta)
print(rho)
cv2_imshow(image1)
cv2_imshow(edges)

This is the ouput:

theta: 0.9773844

rho: 311.0

enter image description here enter image description here

So, when I try to rotate this image with this line and then show it:

img_rotated = ndimage.rotate(image1, theta)
cv2_imshow(img_rotated)

This is the output:

enter image description here

This result does not agree with the rotation that it should be for the frame to be horizontal. Any advise? What am I doing wrong?


Solution

  • In ndimage.rotate angle in degrees.

    img_rotated = ndimage.rotate(image1, 180*theta/3.1415926)