1

假设我有这样的图像:

在此处输入图像描述

我想要图像矩阵中黑条的起点和终点的位置

我尝试了几种方法,例如Python OpenCV 中的水平线检测,并提出了以下代码,使我突出显示了这些行:

import cv2
import numpy as np
from numpy import array
from matplotlib import pyplot as plt
import math

img = cv2.imread('caption.jpg')

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150, apertureSize = 3)
lines = cv2.HoughLinesP(edges, 1,np.pi/180,350);
for line in lines[0]:
    pt1 = (line[0],line[1])
    pt2 = (line[2],line[3])
    cv2.line(img, pt1, pt2, (0,0,255))



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

print img.shape

lines = cv2.HoughLines(edges,1,np.pi/180,350)

for rho,theta in lines[0]:
    a = np.cos(theta)
    b = np.sin(theta)
    if int(b) == 1: #only horizontal lines with cos theta(theta = 0) = 1
        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(img,(x1,y1),(x2,y2),(0,0,255),2)

cv2.imshow('edges', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

结果: 在此处输入图像描述

如果我尝试print x1, y1, x2, y2我得到

-1000 781 999 782 -1000 712 999 713

所以这些显然不是图像矩阵中的位置点,比如 x 是负数。

这些线的起点和终点在图像矩阵中的位置是什么?我需要对该区域的像素执行一些点操作,因此需要起点和终点。

4

1 回答 1

1

这些行将始终返回 -1000 + 原点

x1 = int(x0 + 1000*(-b))
x2 = int(x0 - 1000*(-b))

因为你只有进入这个循环如果int(b) == 1:

这意味着您需要直接打印 x0,因为上面的行将始终为(x0 + (-1000))在这种情况下 x0 为 0,因为它从图像的左侧开始。

于 2016-09-05T00:25:09.053 回答