如何使用cv2.HoughLinesP()的输出来旋转原始图像?

3
我正在使用cv2.HoughLinesP()函数,它会返回检测到的直线。这些直线大多数情况下能够准确地找到物体的角度。然后,我想根据这些直线旋转原始图像。 我的图片:

enter image description here

我的代码:
import cv2 as cv
import numpy as np
img = cv.imread(img)
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
edges = cv.Canny(gray,50,150,apertureSize = 3)
lines = cv.HoughLinesP(edges,1,np.pi/180,100,minLineLength=100,maxLineGap=10)
for line in lines:
    x1,y1,x2,y2 = line[0]
    cv.line(img,(x1,y1),(x2,y2),(0,255,0),5)
cv2.imshow('', img)
cv2.waitKey()

结果:

enter image description here

我想要的:

enter image description here


1
从线段的端点计算线段的角度和长度。假设您想要横向模式,找到两条较长的线段。然后求它们的角度平均值。然后使用该角度旋转线段。请参考https://math.stackexchange.com/questions/707673/find-angle-in-degrees-from-one-point-to-another-in-2d-space - undefined
为什么不直接获取轮廓,然后通过旋转边界框来获取角度呢?可以参考cv2.findContours()和cv2.minAreaRect()函数。 - undefined
请参阅https://inneka.com/ml/opencv/how-to-straighten-a-rotated-rectangle-area-of-an-image-using-opencv-in-python-2/。 - undefined
1个回答

1

看起来你正在尝试执行倾斜校正。与使用 cv2.HoughLinesP 查找角度并旋转对象不同,你可以使用 cv2.minAreaRect 查找角度,然后使用 cv2.getRotationMatrix2D + cv2.warpAffine 对图像进行去斜校正。

输入 -> 输出

倾斜角
-29.35775375366211

代码

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()

注意:如果需要其他的倾斜校正技术,请参考以下链接:

  1. Python OpenCV倾斜校正

  2. 如何去除图像倾斜

  3. 基于文本方向检测图像取向角度


虽然在大多数情况下这是一个很好的答案,但我之所以使用HoughLines()是因为你建议的方法对我来说从未起作用过。相比之下,HoughLines()总是能得到正确的线条。 - undefined
不要使用HoughlinesP来获取角度,我建议尝试找到整个对象的角度。 - undefined
你认为我应该怎么做呢? - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接