使用cv2.findContours()
可以创建“稀疏”(链近似为简单)或“完整”(链约为无)的轮廓。如何将“稀疏”轮廓转换为“完整”轮廓?在
我没有我的轮廓的源图像(形状是已知的),只有轮廓,他们是“稀疏的”(链约_简单)。从这个“稀疏”表示,我想解决“全”(链约_无)表示,以便我可以使用它来访问其他图像的轮廓强度。在
我的临时解决方案(参见代码片段)是使用cv2.drawContours()
,它从“稀疏”轮廓表示中提取所有轮廓像素。结果是一个图像,我可以从结果图像中提取索引,例如使用np.argwhere()
。在
但是,考虑到{cv2.drawContours()
的变体,或者一个输出“完整”轮廓表示而不是图像的选项。在
我的临时解决方案的另一个问题是它不能保持原始轮廓点的顺序。我想知道cv2.drawContours()
是否能够在将结果展平为图像之前在内部重新创建完整、有效的轮廓?在
opencv中的其他函数是否提供了此功能,这些函数可能是cv2.drawContours()
内部使用的一个更基本的函数?在
import numpy as np
import cv2
# shape (Y,X)
shape = np.array((5, 5))
# sparse contour (X,Y)
sparse_contours = [np.array(
[[[1, 0]],
[[1, 4]],
[[3, 4]],
[[3, 0]]], dtype=np.int32)]
def full_contour_from_contour(shape, contour):
# switch shape from y,x to x,y
shp = shape[[1,0]]
arr = np.zeros(shp, dtype=np.int32)
cv2.drawContours(arr, [contour], 0, 1, 1)
idx = np.argwhere(arr==1)
# reorder Y,X -> X,Y
idx = idx[:, [1, 0]]
# reshape to contour layout
rows, cols = idx.shape
idx = idx.reshape(rows, 1, cols)
return idx.astype(np.int32)
full_contour = full_contour_from_contour(shape, sparse_contour)
# output
# these are correct pixels, with pixels in sparse contour also
# part of the full contour. However, the full contour is not
# necessarily correct or even valid due to
# lost information regarding point sequence along the contour)
[[[1 0]]
[[2 0]]
[[3 0]]
[[1 1]]
[[3 1]]
[[1 2]]
[[3 2]]
[[1 3]]
[[3 3]]
[[1 4]]
[[2 4]]
[[3 4]]]
当您查看文档时:https://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=findcontours#findcontours 它们之间的区别在于CHAIN_approach_NONE存储每个像素,CHAIN_approach_SIMPLE只存储构成轮廓线的端点。因此,您可以简单地构造连接轮廓中每对连续顶点的直线,以获得完整表示的近似值。属于线条的每个像素也属于轮廓。在
与suggestion一致的是,下面是一个似乎可以解决我的问题的代码片段。在
相关问题 更多 >
编程相关推荐