首页 > 解决方案 > 如何在python中导出没有图像的行

问题描述

我正在使用 Houghlines 方法从我的图像创建霍夫线,这将返回预期的结果。除了我想在没有原始导入图像的情况下导出霍夫线。如何?

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)

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

标签: pythonpython-2.7numpycv2

解决方案


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

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)

正确的方法是首先cv21.line()在 for 循环中使用画线。在此之后继续使用保存图像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)

推荐阅读