gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:20:30 25 4
gpt4 key购买 nike

我正在使用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

最佳答案

您似乎正在尝试执行倾斜校正。而不是使用 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 skew correction

  2. How to de-skew an image

  3. Detect image orientation angle based on text direction

关于python - 如何使用 cv2.HoughLinesP() 的输出来旋转原始图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60383011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com