如何解决霍夫变换:如何从投票矩阵中获得线条?
所以我试图用python和c ++实现霍夫变换(使用Pybind11在两种语言之间进行接口)。我在绘制hough空间时看起来不错,但我只是无法从投票矩阵的最大值得到一条线。 这是C ++代码(与我使用PyBind11的外观有些不同):
py::array_t<int> houghTransform(py::array_t<int> image,int angleStep,int angleAmount) {
auto imageBuf = image.mutable_unchecked<3>();
int height = imageBuf.shape(0);
int width = imageBuf.shape(1);
py::array_t<int> edgeMatrix = edgeDetect(imageBuf,height,width);
auto edgeMatrixBuf = edgeMatrix.mutable_unchecked<2>();
int distanceAxis = 2 * sqrt(pow((float) height,2.0) + pow((float) width,2.0));
int angleAxis = angleAmount;
int angleDim = (int) angleAxis / angleStep;
int distanceDim = (int) distanceAxis / 2;
py::array_t<int> votingMatrix = py::array_t<int>({distanceAxis,angleDim});
auto votingMatrixBuf = votingMatrix.mutable_unchecked<2>();
// fill voting matrices with zeros
for(int i=0; i<distanceDim; i++) {
for(int j=0; j<angleDim; j++) {
votingMatrixBuf(i,j) = 0;
}
}
// Vote
for(int x=0; x<edgeMatrixBuf.shape(0); x++) {
for(int y=0; y<edgeMatrixBuf.shape(1); y++) {
if(edgeMatrixBuf(x,y) == 1) {
int counter = 0;
float theta;
float ro;
for(int thetaIdx=0; thetaIdx<=angleAxis; thetaIdx++) {
if(thetaIdx % angleStep == 0) {
counter++;
theta = (float) (thetaIdx) * (M_PI / 180);
ro = distanceDim + std::round((x * cos(theta)) + (y * sin(theta)));
votingMatrixBuf(ro,counter) += 1;
}
}
}
}
}
return votingMatrix;
}
如您所见,函数的参数是图像矩阵,我将其转换为边缘为1且其余为0的矩阵,因此得到了感兴趣的像素。
int angleAmount
是我要尝试的角度范围,而int angleStep
是我真正要使用的那个角度的角度(例如,跳过第二个theta)。但是对于这个示例,我将使用angleAmount = 360和angleStep =1。因此,我将使用从1到360的所有角度。
这是python代码:
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import time
from houghTransform import houghTransform
def apply_hough_transform(image_path: str=""):
image = np.array(Image.open(image_path))
lines = houghTransform(image,1,360)
p = np.unravel_index(lines.argmax(),lines.shape)
max_distance = 2 * np.sqrt(pow(image.shape[0],2) + pow(image.shape[1],2))
ro = p[0] - (max_distance / 2)
theta = p[1] * (np.pi / 180)
a = np.cos(theta)
b = np.sin(theta)
x = a * ro
y = b * ro
pt1 = (int(x + 1000*(-b)),int(y + 1000*(a)))
pt2 = (int(x - 1000*(-b)),int(y - 1000*(a)))
fig,axs = plt.subplots(2)
axs[0].matshow(lines)
axs[0].scatter(p[1],p[0],facecolors="none",edgecolors="r")
axs[1].plot([pt1[0],pt2[0]],[pt1[1],pt2[1]])
axs[1].imshow(image)
plt.show()
apply_hough_transform(image_path="images/black_line.png")
函数houghTransform
与我使用PyBind11导出到Python的c ++代码相同。
这是图像:
我还尝试使用此功能创建该行:
def line(x):
return -(1 / np.arctan(theta)) * (x - ro * np.cos(theta)) + ro * np.sin(theta)
但是它也不起作用。 你能发现我的错误吗?我已经坐了很长时间,所以非常感谢您的帮助!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。