如何在Python中导出没有图像的行

时间:2018-07-18 11:58:35

标签: python python-2.7 numpy cv2

我正在使用Houghlines方法从图像中创建hough线,这将返回预期的结果。除了我要导出没有原始导入图像的霍夫线。怎么做?

import numpy as np
import cv2

in_path  = 'my/tif/file'
out_path = 'my/output/tif/file'

gray = cv2.imread(in_path)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
cv2.imwrite('edges.tif',edges)
minLineLength=10
lines = cv2.HoughLinesP(image=edges,rho=3,theta=np.pi/180, threshold=100,lines=np.array([]), minLineLength=minLineLength,maxLineGap=20)

a,b,c = lines.shape
for i in range(a):
    cv2.line(gray, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (255, 0, 0), 1, cv2.LINE_AA)
    cv2.imwrite(out_path,gray)

是否可以将线条导出为矢量或在普通图像上?

1 个答案:

答案 0 :(得分:0)

首先创建一个具有黑色像素的图像,该黑色像素的形状和数据类型与原始图像相同。然后在该图像上绘制检测到的线条。

black = np.zeros_like(gray) 

这里black是一个数组,其中所有元素均为0。换句话说,它是形状和数据类型与gray相同的黑色图像。

cv2.line(black, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (255, 0, 0), 1, cv2.LINE_AA)
cv2.imwrite(out_path, black)

正确的方法是先在for循环中使用cv21.line()绘制线条。之后,请使用cv2.imwrite()保存图像。

这是您可以运行的完整代码:

import numpy as np
import cv2

in_path  = 'my/tif/file'
out_path = 'my/output/tif/file'

gray = cv2.imread(in_path)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
cv2.imwrite('edges.tif',edges)
minLineLength=10
lines = cv2.HoughLinesP(image=edges,rho=3,theta=np.pi/180, threshold=100,lines=np.array([]), minLineLength=minLineLength,maxLineGap=20)

black = np.zeros_like(gray) 

a,b,c = lines.shape
for i in range(a):
    cv2.line(black, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (255, 0, 0), 1, cv2.LINE_AA)

cv2.imwrite(out_path,gray)